From d510b785b1bfdb198929b4d05a285d3bfa3f1823 Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Fri, 31 May 2013 18:21:32 +0100 Subject: [PATCH] Putting everything back together again :) --- Phaser/Collision.ts | 1702 ---- Phaser/Game.ts | 24 +- Phaser/Motion.ts | 403 +- Phaser/Phaser.csproj | 68 +- Phaser/components/Tile.ts | 14 +- Phaser/components/TilemapLayer.ts | 18 +- Phaser/components/sprite/CollisionMask.ts | 501 -- Phaser/components/sprite/Events.ts | 39 + Phaser/components/sprite/Input.ts | 29 - Phaser/components/sprite/Physics.ts | 108 - Phaser/components/sprite/Properties.ts | 36 - Phaser/gameobjects/Emitter.ts | 88 +- Phaser/gameobjects/GameObjectFactory.ts | 37 +- Phaser/gameobjects/GeomSprite.ts | 645 -- Phaser/gameobjects/OldSprite.ts | 355 - Phaser/gameobjects/Particle.ts | 28 +- Phaser/gameobjects/ScrollZone.ts | 3 +- Phaser/gameobjects/Sprite.ts | 32 +- Phaser/gameobjects/Tilemap.ts | 74 +- Phaser/math/GameMath.ts | 129 +- Phaser/math/LinkedList.ts | 1 - Phaser/{physics => math}/QuadTree.ts | 28 +- Phaser/physics/AABB.ts | 208 - Phaser/physics/Body.ts | 5 +- Phaser/physics/Circle.ts | 216 - Phaser/physics/Fixture.ts | 31 - Phaser/physics/IPhysicsBody.ts | 40 - Phaser/physics/IPhysicsShape.ts | 42 - Phaser/physics/PhysicsManager.ts | 483 +- Phaser/utils/SpriteUtils.ts | 102 +- Tests/Tests.csproj | 12 +- Tests/phaser.js | 9868 ++++++++++++--------- Tests/physics/aabb 1.js | 18 +- Tests/physics/aabb 1.ts | 18 +- Tests/physics/aabb vs aabb 1.js | 32 +- Tests/physics/aabb vs aabb 1.ts | 32 +- Tests/physics/circle 1.js | 42 - Tests/physics/circle 1.ts | 70 - Tests/physics/test 1.js | 42 - Tests/physics/test 1.ts | 70 - Tests/sprites/sprite origin 1.js | 2 +- Tests/sprites/sprite origin 1.ts | 2 +- build/phaser-fx.d.ts | 136 - build/phaser-fx.js | 202 +- build/phaser.d.ts | 5100 ++++++----- build/phaser.js | 9123 +++++++++++-------- 46 files changed, 15176 insertions(+), 15082 deletions(-) delete mode 100644 Phaser/Collision.ts delete mode 100644 Phaser/components/sprite/CollisionMask.ts create mode 100644 Phaser/components/sprite/Events.ts delete mode 100644 Phaser/components/sprite/Input.ts delete mode 100644 Phaser/components/sprite/Physics.ts delete mode 100644 Phaser/components/sprite/Properties.ts delete mode 100644 Phaser/gameobjects/GeomSprite.ts delete mode 100644 Phaser/gameobjects/OldSprite.ts rename Phaser/{physics => math}/QuadTree.ts (97%) delete mode 100644 Phaser/physics/AABB.ts delete mode 100644 Phaser/physics/Circle.ts delete mode 100644 Phaser/physics/Fixture.ts delete mode 100644 Phaser/physics/IPhysicsBody.ts delete mode 100644 Phaser/physics/IPhysicsShape.ts delete mode 100644 Tests/physics/circle 1.js delete mode 100644 Tests/physics/circle 1.ts delete mode 100644 Tests/physics/test 1.js delete mode 100644 Tests/physics/test 1.ts diff --git a/Phaser/Collision.ts b/Phaser/Collision.ts deleted file mode 100644 index 13684b81..00000000 --- a/Phaser/Collision.ts +++ /dev/null @@ -1,1702 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// -/// -/// - -/** -* Phaser - Collision -* -* A set of extremely useful collision and geometry intersection functions. -*/ - -module Phaser { - - export class Collision { - - /** - * Collision constructor - * @param game A reference to the current Game - */ - constructor(game: Game) { - - this._game = game; - - Collision.T_VECTORS = []; - - for (var i = 0; i < 10; i++) - { - Collision.T_VECTORS.push(new Vec2); - } - - Collision.T_ARRAYS = []; - - for (var i = 0; i < 5; i++) - { - Collision.T_ARRAYS.push([]); - } - - } - - /** - * Local private reference to Game - */ - private _game: Game; - - /** - * Flag used to allow GameObjects to collide on their left side - * @type {number} - */ - public static LEFT: number = 0x0001; - - /** - * Flag used to allow GameObjects to collide on their right side - * @type {number} - */ - public static RIGHT: number = 0x0010; - - /** - * Flag used to allow GameObjects to collide on their top side - * @type {number} - */ - public static UP: number = 0x0100; - - /** - * Flag used to allow GameObjects to collide on their bottom side - * @type {number} - */ - public static DOWN: number = 0x1000; - - /** - * Flag used with GameObjects to disable collision - * @type {number} - */ - public static NONE: number = 0; - - /** - * Flag used to allow GameObjects to collide with a ceiling - * @type {number} - */ - public static CEILING: number = Collision.UP; - - /** - * Flag used to allow GameObjects to collide with a floor - * @type {number} - */ - public static FLOOR: number = Collision.DOWN; - - /** - * Flag used to allow GameObjects to collide with a wall (same as LEFT+RIGHT) - * @type {number} - */ - public static WALL: number = Collision.LEFT | Collision.RIGHT; - - /** - * Flag used to allow GameObjects to collide on any face - * @type {number} - */ - public static ANY: number = Collision.LEFT | Collision.RIGHT | Collision.UP | Collision.DOWN; - - /** - * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects - * @type {number} - */ - public static OVERLAP_BIAS: number = 4; - - /** - * This holds the result of the tile separation check, true if the object was moved, otherwise false - * @type {boolean} - */ - public static TILE_OVERLAP: bool = false; - - /** - * A temporary Rectangle used in the separation process to help avoid gc spikes - * @type {Rectangle} - */ - public static _tempBounds: Rectangle; - - /** - * 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 - */ - public static lineToLine(line1: Line, line2: Line, output?: IntersectResult = new IntersectResult): 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; - } - - /** - * 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 - */ - public static lineToLineSegment(line: Line, seg: Line, output?: IntersectResult = new IntersectResult): IntersectResult { - - var denominator = (line.x1 - line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 - seg.x2); - - if (denominator !== 0) - { - output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.x1 - seg.x2) - (line.x1 - line.x2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; - output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; - - var maxX = Math.max(seg.x1, seg.x2); - var minX = Math.min(seg.x1, seg.x2); - var maxY = Math.max(seg.y1, seg.y2); - var minY = Math.min(seg.y1, seg.y2); - - if ((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) - { - output.result = true; - } - - } - - return output; - - } - - /** - * 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 - */ - public static lineToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output?: IntersectResult = new IntersectResult): IntersectResult { - - var denominator = (line.x1 - line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 - x2); - - if (denominator !== 0) - { - output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (x1 - x2) - (line.x1 - line.x2) * (x1 * y2 - y1 * x2)) / denominator; - output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 * y2 - y1 * x2)) / denominator; - - var maxX = Math.max(x1, x2); - var minX = Math.min(x1, x2); - var maxY = Math.max(y1, y2); - var minY = Math.min(y1, y2); - - if ((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) - { - output.result = true; - } - - } - - return output; - - } - - /** - * 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 - */ - public static lineToRay(line1: Line, ray: Line, output?: IntersectResult = new IntersectResult): 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; - - } - - - /** - * 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 - */ - public static lineToCircle(line: Line, circle: Circle, output?: IntersectResult = new IntersectResult): 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; - - } - - /** - * 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 - */ - public static lineToRectangle(line: Line, rect: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - // Top of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.y, rect.right, rect.y, output); - - if (output.result === true) - { - return output; - } - - // Left of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.y, rect.x, rect.bottom, output); - - if (output.result === true) - { - return output; - } - - // Bottom of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.x, rect.bottom, rect.right, rect.bottom, output); - - if (output.result === true) - { - return output; - } - - // Right of the Rectangle vs the Line - Collision.lineToRawSegment(line, rect.right, rect.y, rect.right, rect.bottom, output); - - return output; - - } - - /** - * 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 - */ - public static lineSegmentToLineSegment(line1: Line, line2: Line, output?: IntersectResult = new IntersectResult): IntersectResult { - - Collision.lineToLineSegment(line1, line2); - - if (output.result === true) - { - if (!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2) - && output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2))) - { - output.result = false; - } - } - - return output; - } - - /** - * 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 - */ - public static lineSegmentToRay(line: Line, ray: Line, output?: IntersectResult = new IntersectResult): IntersectResult { - - Collision.lineToRay(line, ray, output); - - if (output.result === true) - { - if (!(output.x >= Math.min(line.x1, line.x2) && output.x <= Math.max(line.x1, line.x2) - && output.y >= Math.min(line.y1, line.y2) && output.y <= Math.max(line.y1, line.y2))) - { - output.result = false; - } - } - - return output; - - } - - /** - * 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 - */ - public static lineSegmentToCircle(seg: Line, circle: Circle, output?: IntersectResult = new IntersectResult): IntersectResult { - - var perp = seg.perp(circle.x, circle.y); - - if (perp.length <= circle.radius) - { - // Line intersects circle - check if segment does - var maxX = Math.max(seg.x1, seg.x2); - var minX = Math.min(seg.x1, seg.x2); - var maxY = Math.max(seg.y1, seg.y2); - var minY = Math.min(seg.y1, seg.y2); - - if ((perp.x2 <= maxX && perp.x2 >= minX) && (perp.y2 <= maxY && perp.y2 >= minY)) - { - output.result = true; - } - else - { - // Worst case - segment doesn't traverse center, so no perpendicular connection. - if (Collision.circleContainsPoint(circle, { x: seg.x1, y: seg.y1 }) || Collision.circleContainsPoint(circle, { x: seg.x2, y: seg.y2 })) - { - output.result = true; - } - } - - } - - return output; - } - - /** - * 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 - */ - public static lineSegmentToRectangle(seg: Line, rect: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - if (rect.contains(seg.x1, seg.y1) && rect.contains(seg.x2, seg.y2)) - { - output.result = true; - } - else - { - // Top of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.y, rect.right, rect.bottom, output); - - if (output.result === true) - { - return output; - } - - // Left of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.y, rect.x, rect.bottom, output); - - if (output.result === true) - { - return output; - } - - // Bottom of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.x, rect.bottom, rect.right, rect.bottom, output); - - if (output.result === true) - { - return output; - } - - // Right of the Rectangle vs the Line - Collision.lineToRawSegment(seg, rect.right, rect.y, rect.right, rect.bottom, output); - - return output; - - } - - return output; - - } - - /** - * 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 - */ - public static rayToRectangle(ray: Line, rect: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - // Currently just finds first intersection - might not be closest to ray pt1 - Collision.lineToRectangle(ray, rect, output); - - return output; - - } - - - /** - * 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 - */ - public static rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output?: IntersectResult = new IntersectResult): IntersectResult { - - var r:number; - var s:number; - var d:number; - - // 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; - - } - - /** - * 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 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 - */ - public static pointToRectangle(point, rect: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - output.setTo(point.x, point.y); - - //output.result = rect.containsPoint(point); - - - return output; - - } - - /** - * 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 - */ - public static rectangleToRectangle(rect1: Rectangle, rect2: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - var leftX = Math.max(rect1.x, rect2.x); - var rightX = Math.min(rect1.right, rect2.right); - var topY = Math.max(rect1.y, rect2.y); - var bottomY = Math.min(rect1.bottom, rect2.bottom); - - output.setTo(leftX, topY, rightX - leftX, bottomY - topY, rightX - leftX, bottomY - topY); - - var cx = output.x + output.width * .5; - var cy = output.y + output.height * .5; - - if ((cx > rect1.x && cx < rect1.right) && (cy > rect1.y && cy < rect1.bottom)) - { - output.result = true; - } - - return output; - - } - - /** - * 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 - */ - public static rectangleToCircle(rect: Rectangle, circle: Circle, output?: IntersectResult = new IntersectResult): IntersectResult { - - return Collision.circleToRectangle(circle, rect, output); - - } - - /** - * 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 - */ - public static circleToCircle(circle1: Circle, circle2: Circle, output?: IntersectResult = new IntersectResult): IntersectResult { - - output.result = ((circle1.radius + circle2.radius) * (circle1.radius + circle2.radius)) >= Collision.distanceSquared(circle1.x, circle1.y, circle2.x, circle2.y); - - return output; - - } - - /** - * 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 - */ - public static circleToRectangle(circle: Circle, rect: Rectangle, output?: IntersectResult = new IntersectResult): IntersectResult { - - var inflatedRect: Rectangle = rect.clone(); - - inflatedRect.inflate(circle.radius, circle.radius); - - output.result = inflatedRect.contains(circle.x, circle.y); - - return output; - - } - - /** - * 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 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 - */ - public static circleContainsPoint(circle: Circle, point, output?: IntersectResult = new IntersectResult): IntersectResult { - - output.result = circle.radius * circle.radius >= Collision.distanceSquared(circle.x, circle.y, point.x, point.y); - - return output; - - } - - /** - * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. - * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. - * @param object1 The first GameObject or Group to check. If null the world.group is used. - * @param object2 The second GameObject or Group to check. - * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. - * @param context The context in which the callbacks will be called - * @returns {boolean} true if the objects overlap, otherwise false. - */ - public overlap(object1: Basic = null, object2: Basic = null, notifyCallback = null, processCallback = null, context = null): bool { - - if (object1 == null) - { - object1 = this._game.world.group; - } - - if (object2 == object1) - { - object2 = null; - } - - QuadTree.divisions = this._game.world.worldDivisions; - - var quadTree: QuadTree = new 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: bool = quadTree.execute(); - - quadTree.destroy(); - - quadTree = null; - - return result; - - } - - /** - * 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. - */ - public static separate(object1, object2): bool { - - object1.collisionMask.update(); - object2.collisionMask.update(); - - var separatedX: bool = Collision.separateX(object1, object2); - var separatedY: bool = Collision.separateY(object1, object2); - - return separatedX || separatedY; - - } - - /** - * 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 - */ - public static separateTile(object:GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool, separateX: bool, separateY: bool): bool { - - object.collisionMask.update(); - - var separatedX: bool = Collision.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); - var separatedY: bool = Collision.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); - - return separatedX || separatedY; - - } - - /** - * 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. - */ - public static separateTileX(object:GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { - - // Can't separate two immovable objects (tiles are always immovable) - if (object.immovable) - { - return false; - } - - // First, get the object delta - var overlap: number = 0; - var objDelta: number = object.x - object.last.x; - //var objDelta: number = object.collisionMask.deltaX; - - if (objDelta != 0) - { - // Check if the X hulls actually overlap - var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; - //var objDeltaAbs: number = object.collisionMask.deltaXAbs; - 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)) - { - var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (objDelta > 0) - { - overlap = object.x + object.width - x; - - if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.RIGHT; - } - } - else if (objDelta < 0) - { - overlap = object.x - width - x; - - if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.LEFT; - } - - } - - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - if (separate == true) - { - //console.log(' - object.x = object.x - overlap; - object.velocity.x = -(object.velocity.x * object.elasticity); - } - - Collision.TILE_OVERLAP = true; - return true; - } - else - { - return false; - } - - } - - /** - * 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. - */ - public static separateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { - - // Can't separate two immovable objects (tiles are always immovable) - if (object.immovable) - { - return false; - } - - // First, get the two object deltas - var overlap: number = 0; - var objDelta: number = object.y - object.last.y; - - if (objDelta != 0) - { - // Check if the Y hulls actually overlap - var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; - 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)) - { - var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (objDelta > 0) - { - overlap = object.y + object.height - y; - - if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.DOWN; - } - } - else if (objDelta < 0) - { - overlap = object.y - height - y; - - if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.UP; - } - } - } - } - - // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - if (separate == true) - { - object.y = object.y - overlap; - object.velocity.y = -(object.velocity.y * object.elasticity); - } - - Collision.TILE_OVERLAP = true; - return true; - } - else - { - return false; - } - } - - - /** - * 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. - */ - public static NEWseparateTileX(object:GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { - - // Can't separate two immovable objects (tiles are always immovable) - if (object.immovable) - { - return false; - } - - // First, get the object delta - var overlap: number = 0; - - if (object.collisionMask.deltaX != 0) - { - // Check if the X hulls actually overlap - //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; - //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)) - { - var maxOverlap: number = object.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (object.collisionMask.deltaX > 0) - { - //overlap = object.x + object.width - x; - overlap = object.collisionMask.right - x; - - if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.RIGHT; - } - } - else if (object.collisionMask.deltaX < 0) - { - //overlap = object.x - width - x; - overlap = object.collisionMask.x - width - x; - - if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.LEFT; - } - - } - - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - if (separate == true) - { - object.x = object.x - overlap; - object.velocity.x = -(object.velocity.x * object.elasticity); - } - - Collision.TILE_OVERLAP = true; - return true; - } - else - { - return false; - } - - } - - /** - * 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. - */ - public static NEWseparateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { - - // Can't separate two immovable objects (tiles are always immovable) - if (object.immovable) - { - return false; - } - - // First, get the two object deltas - var overlap: number = 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: 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)) - { - //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; - var maxOverlap: number = object.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (object.collisionMask.deltaY > 0) - { - //overlap = object.y + object.height - y; - overlap = object.collisionMask.bottom - y; - - if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.DOWN; - } - } - else if (object.collisionMask.deltaY < 0) - { - //overlap = object.y - height - y; - overlap = object.collisionMask.y - height - y; - - if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) - { - overlap = 0; - } - else - { - object.touching |= Collision.UP; - } - } - } - } - - // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - if (separate == true) - { - object.y = object.y - overlap; - object.velocity.y = -(object.velocity.y * object.elasticity); - } - - Collision.TILE_OVERLAP = true; - return true; - } - else - { - return false; - } - } - - /** - * 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. - */ - public static separateX(object1, object2): bool { - - // Can't separate two immovable objects - if (object1.immovable && object2.immovable) - { - return false; - } - - // First, get the two object deltas - var overlap: number = 0; - - if (object1.collisionMask.deltaX != object2.collisionMask.deltaX) - { - if (object1.collisionMask.intersects(object2.collisionMask)) - { - var maxOverlap: number = object1.collisionMask.deltaXAbs + object2.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (object1.collisionMask.deltaX > object2.collisionMask.deltaX) - { - overlap = object1.collisionMask.right - object2.collisionMask.x; - - if ((overlap > maxOverlap) || !(object1.allowCollisions & Collision.RIGHT) || !(object2.allowCollisions & Collision.LEFT)) - { - overlap = 0; - } - else - { - object1.touching |= Collision.RIGHT; - object2.touching |= Collision.LEFT; - } - } - else if (object1.collisionMask.deltaX < object2.collisionMask.deltaX) - { - overlap = object1.collisionMask.x - object2.collisionMask.width - object2.collisionMask.x; - - if ((-overlap > maxOverlap) || !(object1.allowCollisions & Collision.LEFT) || !(object2.allowCollisions & Collision.RIGHT)) - { - overlap = 0; - } - else - { - object1.touching |= Collision.LEFT; - object2.touching |= Collision.RIGHT; - } - - } - - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - var obj1Velocity: number = object1.velocity.x; - var obj2Velocity: number = object2.velocity.x; - - if (!object1.immovable && !object2.immovable) - { - overlap *= 0.5; - object1.x = object1.x - overlap; - object2.x += overlap; - - var obj1NewVelocity: number = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity: number = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average: number = (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; - } - - } - - /** - * 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. - */ - public static separateY(object1, object2): bool { - - // Can't separate two immovable objects - if (object1.immovable && object2.immovable) { - return false; - } - - // First, get the two object deltas - var overlap: number = 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: number = object1.collisionMask.deltaYAbs + object2.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; - - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if (object1.collisionMask.deltaY > object2.collisionMask.deltaY) - { - overlap = object1.collisionMask.bottom - object2.collisionMask.y; - - if ((overlap > maxOverlap) || !(object1.allowCollisions & Collision.DOWN) || !(object2.allowCollisions & Collision.UP)) - { - overlap = 0; - } - else - { - object1.touching |= Collision.DOWN; - object2.touching |= Collision.UP; - } - } - else if (object1.collisionMask.deltaY < object2.collisionMask.deltaY) - { - overlap = object1.collisionMask.y - object2.collisionMask.height - object2.collisionMask.y; - - if ((-overlap > maxOverlap) || !(object1.allowCollisions & Collision.UP) || !(object2.allowCollisions & Collision.DOWN)) - { - overlap = 0; - } - else - { - object1.touching |= Collision.UP; - object2.touching |= Collision.DOWN; - } - } - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (overlap != 0) - { - var obj1Velocity: number = object1.velocity.y; - var obj2Velocity: number = object2.velocity.y; - - if (!object1.immovable && !object2.immovable) - { - overlap *= 0.5; - object1.y = object1.y - overlap; - object2.y += overlap; - - var obj1NewVelocity: number = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity: number = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average: number = (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; - } - } - - /** - * 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 - */ - public static distance(x1: number, y1: number, x2: number, y2: number) { - return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); - } - - /** - * 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 - */ - public static distanceSquared(x1: number, y1: number, x2: number, y2: number) { - return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); - } - - - - // 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. - */ - public static 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; - - } - - /** - * Pool of Vectors used in calculations. - * - * @type {Array.} - */ - public static T_VECTORS: Vec2[]; - - /** - * Pool of Arrays used in calculations. - * - * @type {Array.>} - */ - public static T_ARRAYS; - - /** - * Check whether two convex clockwise polygons are separated by the specified - * axis (must be a unit vector). - * - * @param {Vector} aPos The position of the first polygon. - * @param {Vector} bPos The position of the second polygon. - * @param {Array.} aPoints The points in the first polygon. - * @param {Array.} bPoints The points in the second polygon. - * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons - * will be projected onto this axis. - * @param {Response=} response A Response object (optional) which will be populated - * if the axis is not a separating axis. - * @return {boolean} true if it is a separating axis, false otherwise. If false, - * and a response is passed in, information about how much overlap and - * the direction of the overlap will be populated. - */ - public static isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response?:Response = null): bool { - - var rangeA = Collision.T_ARRAYS.pop(); - var rangeB = Collision.T_ARRAYS.pop(); - - // Get the magnitude of the offset between the two polygons - var offsetV = Collision.T_VECTORS.pop().copyFrom(bPos).sub(aPos); - var projectedOffset = offsetV.dot(axis); - - // Project the polygons onto the axis. - Collision.flattenPointsOn(aPoints, axis, rangeA); - Collision.flattenPointsOn(bPoints, axis, rangeB); - - // Move B's range to its position relative to A. - rangeB[0] += projectedOffset; - rangeB[1] += projectedOffset; - - // Check if there is a gap. If there is, this is a separating axis and we can stop - if (rangeA[0] > rangeB[1] || rangeB[0] > rangeA[1]) - { - Collision.T_VECTORS.push(offsetV); - Collision.T_ARRAYS.push(rangeA); - Collision.T_ARRAYS.push(rangeB); - return true; - } - - // If we're calculating a response, calculate the overlap. - if (response) - { - var overlap = 0; - - // A starts further left than B - if (rangeA[0] < rangeB[0]) - { - response.aInB = false; - - // A ends before B does. We have to pull A out of B - if (rangeA[1] < rangeB[1]) - { - overlap = rangeA[1] - rangeB[0]; - response.bInA = false; - // B is fully inside A. Pick the shortest way out. - } - else - { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - // B starts further left than A - } - else - { - response.bInA = false; - - // B ends before A ends. We have to push A out of B - if (rangeA[1] > rangeB[1]) - { - overlap = rangeA[0] - rangeB[1]; - response.aInB = false; - // A is fully inside B. Pick the shortest way out. - } - else - { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - } - - // If this is the smallest amount of overlap we've seen so far, set it as the minimum overlap. - var absOverlap = Math.abs(overlap); - - if (absOverlap < response.overlap) - { - response.overlap = absOverlap; - response.overlapN.copyFrom(axis); - - if (overlap < 0) - { - response.overlapN.reverse(); - } - } - } - - Collision.T_VECTORS.push(offsetV); - Collision.T_ARRAYS.push(rangeA); - Collision.T_ARRAYS.push(rangeB); - - return false; - - } - - public static LEFT_VORNOI_REGION:number = -1; - public static MIDDLE_VORNOI_REGION:number = 0; - public static RIGHT_VORNOI_REGION:number = 1; - - /** - * 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. - */ - public static vornoiRegion(line: Vec2, point: Vec2): number { - - var len2 = line.length2(); - var dp = point.dot(line); - - if (dp < 0) { return Collision.LEFT_VORNOI_REGION; } - else if (dp > len2) { return Collision.RIGHT_VORNOI_REGION; } - else { return Collision.MIDDLE_VORNOI_REGION; } - - } - - /** - * 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. - */ - public static testCircleCircle(a: Circle, b: Circle, response?: Response = null): bool { - - var differenceV = Collision.T_VECTORS.pop().copyFrom(b.pos).sub(a.pos); - var totalRadius = a.radius + b.radius; - var totalRadiusSq = totalRadius * totalRadius; - var distanceSq = differenceV.length2(); - - if (distanceSq > totalRadiusSq) - { - // They do not intersect - Collision.T_VECTORS.push(differenceV); - return false; - } - - // They intersect. If we're calculating a response, calculate the overlap. - if (response) - { - var dist = Math.sqrt(distanceSq); - response.a = a; - response.b = b; - response.overlap = totalRadius - dist; - response.overlapN.copyFrom(differenceV.normalize()); - response.overlapV.copyFrom(differenceV).scale(response.overlap); - response.aInB = a.radius <= b.radius && dist <= b.radius - a.radius; - response.bInA = b.radius <= a.radius && dist <= a.radius - b.radius; - } - - Collision.T_VECTORS.push(differenceV); - return true; - - } - - /** - * 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. - */ - public static testPolygonCircle(polygon: Polygon, circle: Circle, response?: Response = null): bool { - - var circlePos = Collision.T_VECTORS.pop().copyFrom(circle.pos).sub(polygon.pos); - var radius = circle.radius; - var radius2 = radius * radius; - var points = polygon.points; - var len = points.length; - var edge = T_VECTORS.pop(); - var point = 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 = vornoiRegion(edge, point); - - if (region === Collision.LEFT_VORNOI_REGION) - { - // Need to make sure we're in the RIGHT_VORNOI_REGION of the previous edge. - edge.copyFrom(polygon.edges[prev]); - - // Calculate the center of the circle relative the starting point of the previous edge - var point2 = Collision.T_VECTORS.pop().copyFrom(circlePos).sub(points[prev]); - region = vornoiRegion(edge, point2); - - if (region === Collision.RIGHT_VORNOI_REGION) - { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.length2(); - - if (dist > radius) - { - // No intersection - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - Collision.T_VECTORS.push(point2); - return false; - } - else if (response) - { - // It intersects, calculate the overlap - response.bInA = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - - Collision.T_VECTORS.push(point2); - - } - else if (region === Collision.RIGHT_VORNOI_REGION) - { - // Need to make sure we're in the left region on the next edge - edge.copyFrom(polygon.edges[next]); - - // Calculate the center of the circle relative to the starting point of the next edge - point.copyFrom(circlePos).sub(points[next]); - region = vornoiRegion(edge, point); - - if (region === Collision.LEFT_VORNOI_REGION) - { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.length2(); - - if (dist > radius) - { - // No intersection - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - return false; - } - else if (response) - { - // It intersects, calculate the overlap - response.bInA = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - // MIDDLE_VORNOI_REGION - } - else - { - // Need to check if the circle is intersecting the edge, - // Change the edge into its "edge normal". - var normal = edge.perp().normalize(); - - // Find the perpendicular distance between the center of the - // circle and the edge. - var dist = point.dot(normal); - var distAbs = Math.abs(dist); - - // If the circle is on the outside of the edge, there is no intersection - if (dist > 0 && distAbs > radius) - { - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(normal); - Collision.T_VECTORS.push(point); - return false; - } - else if (response) - { - // It intersects, calculate the overlap. - overlapN = normal; - overlap = radius - dist; - // If the center of the circle is on the outside of the edge, or part of the - // circle is on the outside, the circle is not fully inside the polygon. - if (dist >= 0 || overlap < 2 * radius) - { - response.bInA = false; - } - } - } - - // If this is the smallest overlap we've seen, keep it. - // (overlapN may be null if the circle was in the wrong Vornoi region) - if (overlapN && response && Math.abs(overlap) < Math.abs(response.overlap)) - { - response.overlap = overlap; - response.overlapN.copyFrom(overlapN); - } - } - - // Calculate the final overlap vector - based on the smallest overlap. - if (response) - { - response.a = polygon; - response.b = circle; - response.overlapV.copyFrom(response.overlapN).scale(response.overlap); - } - - Collision.T_VECTORS.push(circlePos); - Collision.T_VECTORS.push(edge); - Collision.T_VECTORS.push(point); - - return true; - } - - /** - * 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. - */ - public static testCirclePolygon(circle: Circle, polygon: Polygon, response?: Response = null): bool { - - var result = Collision.testPolygonCircle(polygon, circle, response); - - if (result && response) - { - // Swap A and B in the response. - var a = response.a; - var aInB = response.aInB; - response.overlapN.reverse(); - response.overlapV.reverse(); - response.a = response.b; - response.b = a; - response.aInB = response.bInA; - response.bInA = aInB; - } - - return result; - } - - /** - * 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. - */ - public static testPolygonPolygon(a: Polygon, b: Polygon, response?: Response = null): bool { - - var aPoints = a.points; - var aLen = aPoints.length; - var bPoints = b.points; - var bLen = bPoints.length; - - // If any of the edge normals of A is a separating axis, no intersection. - for (var i = 0; i < aLen; i++) - { - if (Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, a.normals[i], response)) - { - return false; - } - } - - // If any of the edge normals of B is a separating axis, no intersection. - for (var i = 0; i < bLen; i++) - { - if (Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, b.normals[i], response)) - { - return false; - } - } - - // Since none of the edge normals of A or B are a separating axis, there is an intersection - // and we've already calculated the smallest overlap (in isSeparatingAxis). Calculate the - // final overlap vector. - if (response) - { - response.a = a; - response.b = b; - response.overlapV.copyFrom(response.overlapN).scale(response.overlap); - } - - return true; - } - - } - -} \ No newline at end of file diff --git a/Phaser/Game.ts b/Phaser/Game.ts index fb147c58..9c887f1c 100644 --- a/Phaser/Game.ts +++ b/Phaser/Game.ts @@ -1,17 +1,24 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// /// /// /// /// -/// -/// -/// /// /// /// /// /// +/// /// /// /// @@ -169,12 +176,6 @@ module Phaser { */ public cache: Cache; - /** - * Reference to the collision helper. - * @type {Collision} - */ - //public collision: Collision; - /** * Reference to the input manager * @type {Input} @@ -197,7 +198,7 @@ module Phaser { * Reference to the motion helper. * @type {Motion} */ - //public motion: Motion; + public motion: Motion; /** * Reference to the sound manager. @@ -279,14 +280,13 @@ 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.loader = new Loader(this, this.loadComplete); this.time = new Time(this); this.tweens = new TweenManager(this); diff --git a/Phaser/Motion.ts b/Phaser/Motion.ts index 6d91c688..54098b6b 100644 --- a/Phaser/Motion.ts +++ b/Phaser/Motion.ts @@ -1,5 +1,5 @@ /// -/// +/// /** * Phaser - Motion @@ -12,62 +12,10 @@ module Phaser { export class Motion { constructor(game: Game) { - - this._game = game; - + this.game = game; } - private _game: Game; - - /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. - * - * @param {number} Velocity Any component of velocity (e.g. 20). - * @param {number} Acceleration Rate at which the velocity is changing. - * @param {number} Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. - * @param {number} Max An absolute value cap for the velocity. - * - * @return {number} The altered Velocity value. - */ - public computeVelocity(Velocity: number, Acceleration: number = 0, Drag: number = 0, Max: number = 10000): number { - - if (Acceleration !== 0) - { - Velocity += Acceleration * this._game.time.elapsed; - } - else if (Drag !== 0) - { - var drag: number = Drag * this._game.time.elapsed; - - if (Velocity - drag > 0) - { - Velocity = Velocity - drag; - } - else if (Velocity + drag < 0) - { - Velocity += drag; - } - else - { - Velocity = 0; - } - } - - if ((Velocity != 0) && (Max != 10000)) - { - if (Velocity > Max) - { - Velocity = Max; - } - else if (Velocity < -Max) - { - Velocity = -Max; - } - } - - return Velocity; - - } + public game: Game; /** * Given the angle and speed calculate the velocity and return it as a Point @@ -84,13 +32,13 @@ module Phaser { speed = 0; } - var a: number = this._game.math.degreesToRadians(angle); + var a: number = this.game.math.degreesToRadians(angle); return new Point((Math.cos(a) * speed), (Math.sin(a) * speed)); } - /** + /** * 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.
@@ -98,311 +46,296 @@ module Phaser { * 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 {Sprite} source The Sprite on which the velocity will be set + * @param {Sprite} dest The Sprite where the source object will move to * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms */ - public moveTowardsObject(source:GameObject, dest:GameObject, speed:number= 60, maxTime:number = 0) - { - var a:number = this.angleBetween(source, dest); + public moveTowardsObject(source: Sprite, dest: Sprite, speed: number = 60, maxTime: number = 0) { + var a: number = this.angleBetween(source, dest); - if (maxTime > 0) - { - var d:number = this.distanceBetween(source, dest); + if (maxTime > 0) + { + var d: number = this.distanceBetween(source, dest); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; + source.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; - } + } - /** + /** * 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 {Sprite} source The Sprite on which the acceleration will be set + * @param {Sprite} dest The Sprite where the source object will move towards * @param {number} speed The speed it will accelerate in pixels per second * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically */ - public accelerateTowardsObject(source:GameObject, dest:GameObject, speed:number, xSpeedMax:number, ySpeedMax:number) - { - var a:number = this.angleBetween(source, dest); + public accelerateTowardsObject(source: Sprite, dest: Sprite, speed: number, xSpeedMax: number, ySpeedMax: number) { + var a: number = this.angleBetween(source, dest); - source.velocity.x = 0; - source.velocity.y = 0; + source.body.velocity.x = 0; + source.body.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; + source.body.maxVelocity.x = xSpeedMax; + source.body.maxVelocity.y = ySpeedMax; - } + } - /** + /** * 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 {Sprite} source The Sprite to move * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms */ - public moveTowardsMouse(source:GameObject, speed:number = 60, maxTime:number = 0) - { - var a:number = this.angleBetweenMouse(source); + public moveTowardsMouse(source: Sprite, speed: number = 60, maxTime: number = 0) { + var a: number = this.angleBetweenMouse(source); - if (maxTime > 0) - { - var d:number = this.distanceToMouse(source); + if (maxTime > 0) + { + var d: number = this.distanceToMouse(source); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; + source.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; - } + } - /** + /** * 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 {Sprite} source The Sprite on which the acceleration will be set * @param {number} speed The speed it will accelerate in pixels per second * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically */ - public accelerateTowardsMouse(source:GameObject, speed:number, xSpeedMax:number, ySpeedMax:number) - { - var a:number = this.angleBetweenMouse(source); + public accelerateTowardsMouse(source: Sprite, speed: number, xSpeedMax: number, ySpeedMax: number) { + var a: number = this.angleBetweenMouse(source); - source.velocity.x = 0; - source.velocity.y = 0; + source.body.velocity.x = 0; + source.body.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; - } + source.body.maxVelocity.x = xSpeedMax; + source.body.maxVelocity.y = ySpeedMax; + } - /** + /** * 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 {Sprite} source The Sprite to move * @param {Point} target The Point coordinates to move the source Sprite towards * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms */ - public moveTowardsPoint(source:GameObject, target:Point, speed:number = 60, maxTime:number = 0) - { - var a:number = this.angleBetweenPoint(source, target); + public moveTowardsPoint(source: Sprite, target: Point, speed: number = 60, maxTime: number = 0) { + var a: number = this.angleBetweenPoint(source, target); - if (maxTime > 0) - { - var d:number = this.distanceToPoint(source, target); + if (maxTime > 0) + { + var d: number = this.distanceToPoint(source, target); - // We know how many pixels we need to move, but how fast? - speed = d / (maxTime / 1000); - } + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } - source.velocity.x = Math.cos(a) * speed; - source.velocity.y = Math.sin(a) * speed; - } + source.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + } - /** + /** * 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 {Sprite} source The Sprite on which the acceleration will be set * @param {Point} target The Point coordinates to move the source Sprite towards * @param {number} speed The speed it will accelerate in pixels per second * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically */ - public accelerateTowardsPoint(source:GameObject, target:Point, speed:number, xSpeedMax:number, ySpeedMax:number) - { - var a:number = this.angleBetweenPoint(source, target); + public accelerateTowardsPoint(source: Sprite, target: Point, speed: number, xSpeedMax: number, ySpeedMax: number) { + var a: number = this.angleBetweenPoint(source, target); - source.velocity.x = 0; - source.velocity.y = 0; + source.body.velocity.x = 0; + source.body.velocity.y = 0; - source.acceleration.x = Math.cos(a) * speed; - source.acceleration.y = Math.sin(a) * speed; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; - source.maxVelocity.x = xSpeedMax; - source.maxVelocity.y = ySpeedMax; - } + source.body.maxVelocity.x = xSpeedMax; + source.body.maxVelocity.y = ySpeedMax; + } - /** - * Find the distance (in pixels, rounded) between two Sprites, taking their origin into account + /** + * Find the distance between two Sprites, taking their origin into account * - * @param {GameObject} a The first Sprite - * @param {GameObject} b The second Sprite + * @param {Sprite} a The first Sprite + * @param {Sprite} b The second Sprite * @return {number} int Distance (in pixels) */ - public distanceBetween(a:GameObject, b:GameObject):number - { - var dx:number = (a.x + a.origin.x) - (b.x + b.origin.x); - var dy:number = (a.y + a.origin.y) - (b.y + b.origin.y); + public distanceBetween(a: Sprite, b: Sprite): number { + return Vec2Utils.distance(a.body.position, b.body.position); + } - return this._game.math.vectorLength(dx, dy); - - } - - /** - * Find the distance (in pixels, rounded) from an Sprite to the given Point, taking the source origin into account + /** + * Find the distance from an Sprite to the given Point, taking the source origin into account * - * @param {GameObject} a The Sprite + * @param {Sprite} a The Sprite * @param {Point} target The Point * @return {number} Distance (in pixels) */ - public distanceToPoint(a:GameObject, target:Point):number - { - var dx:number = (a.x + a.origin.x) - (target.x); - var dy:number = (a.y + a.origin.y) - (target.y); + public distanceToPoint(a: Sprite, target: Point): number { + var dx: number = (a.x + a.origin.x) - (target.x); + var dy: number = (a.y + a.origin.y) - (target.y); - return this._game.math.vectorLength(dx, dy); - } + return this.game.math.vectorLength(dx, dy); + } - /** + /** * Find the distance (in pixels, rounded) from the object x/y and the mouse x/y * - * @param {GameObject} a Sprite to test against + * @param {Sprite} a Sprite to test against * @return {number} The distance between the given sprite and the mouse coordinates */ - public distanceToMouse(a:GameObject):number - { - var dx: number = (a.x + a.origin.x) - this._game.input.x; - var dy: number = (a.y + a.origin.y) - this._game.input.y; + public distanceToMouse(a: Sprite): number { + var dx: number = (a.x + a.origin.x) - this.game.input.x; + var dy: number = (a.y + a.origin.y) - this.game.input.y; - return this._game.math.vectorLength(dx, dy); - } + return this.game.math.vectorLength(dx, dy); + } - /** + /** * 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 {Sprite} a The Sprite to test from * @param {Point} target The Point to angle the Sprite towards * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true * * @return {number} The angle (in radians unless asDegrees is true) */ - public angleBetweenPoint(a:GameObject, target:Point, asDegrees:bool = false):number - { - var dx:number = (target.x) - (a.x + a.origin.x); - var dy:number = (target.y) - (a.y + a.origin.y); + public angleBetweenPoint(a: Sprite, target: Point, asDegrees: bool = false): number { + var dx: number = (target.x) - (a.x + a.origin.x); + var dy: number = (target.y) - (a.y + a.origin.y); - if (asDegrees) - { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } - else - { - return Math.atan2(dy, dx); - } + if (asDegrees) + { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } + else + { + return Math.atan2(dy, dx); + } } - /** + /** * 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 {Sprite} a The Sprite to test from + * @param {Sprite} b The Sprite to test to * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true * * @return {number} The angle (in radians unless asDegrees is true) */ - public angleBetween(a:GameObject, b:GameObject, asDegrees:bool = false):number - { - var dx:number = (b.x + b.origin.x) - (a.x + a.origin.x); - var dy:number = (b.y + b.origin.y) - (a.y + a.origin.y); + public angleBetween(a: Sprite, b: Sprite, asDegrees: bool = false): number { - if (asDegrees) - { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } - else - { - return Math.atan2(dy, dx); - } + var dx: number = (b.x + b.origin.x) - (a.x + a.origin.x); + var dy: number = (b.y + b.origin.y) - (a.y + a.origin.y); + + if (asDegrees) + { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } + else + { + return Math.atan2(dy, dx); + } } - /** - * Given the GameObject and speed calculate the velocity and return it as an Point based on the direction the sprite is facing + /** + * Given the Sprite 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 {Sprite} parent The Sprite to get the facing value from * @param {number} speed The speed it will move, in pixels per second sq * * @return {Point} An Point where Point.x contains the velocity x value and Point.y contains the velocity y value */ - public velocityFromFacing(parent:GameObject, speed:number):Point - { - var a:number; + public velocityFromFacing(parent: Sprite, speed: number): Point { + var a: number; - if (parent.facing == Collision.LEFT) - { - a = this._game.math.degreesToRadians(180); - } - else if (parent.facing == Collision.RIGHT) - { - a = this._game.math.degreesToRadians(0); - } - else if (parent.facing == Collision.UP) - { - a = this._game.math.degreesToRadians(-90); - } - else if (parent.facing == Collision.DOWN) - { - a = this._game.math.degreesToRadians(90); - } + if (parent.body.facing == Types.LEFT) + { + a = this.game.math.degreesToRadians(180); + } + else if (parent.body.facing == Types.RIGHT) + { + a = this.game.math.degreesToRadians(0); + } + else if (parent.body.facing == Types.UP) + { + a = this.game.math.degreesToRadians(-90); + } + else if (parent.body.facing == Types.DOWN) + { + a = this.game.math.degreesToRadians(90); + } - return new Point(Math.cos(a) * speed, Math.sin(a) * speed); + return new Point(Math.cos(a) * speed, Math.sin(a) * speed); - } + } - /** + /** * 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 {Sprite} a The Object to test from * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true * * @return {number} The angle (in radians unless asDegrees is true) */ - public angleBetweenMouse(a:GameObject, asDegrees:bool = false):number - { - // In order to get the angle between the object and mouse, we need the objects screen coordinates (rather than world coordinates) - var p:MicroPoint = a.getScreenXY(); + public angleBetweenMouse(a: Sprite, asDegrees: bool = false): number { - var dx:number = a._game.input.x - p.x; - var dy:number = a._game.input.y - p.y; + // In order to get the angle between the object and mouse, we need the objects screen coordinates (rather than world coordinates) + var p: Point = SpriteUtils.getScreenXY(a); - if (asDegrees) - { - return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); - } - else - { - return Math.atan2(dy, dx); - } - } + var dx: number = a.game.input.x - p.x; + var dy: number = a.game.input.y - p.y; + + if (asDegrees) + { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } + else + { + return Math.atan2(dy, dx); + } + } } diff --git a/Phaser/Phaser.csproj b/Phaser/Phaser.csproj index bffdefb0..c9526df2 100644 --- a/Phaser/Phaser.csproj +++ b/Phaser/Phaser.csproj @@ -61,7 +61,20 @@ AnimationManager.ts - + + + + + Debug.ts + + + Events.ts + + + + + Game.ts + @@ -90,15 +103,21 @@ DynamicTexture.ts - - Game.ts - + + + Emitter.ts + IGameObject.ts + + + + Tilemap.ts + GameMath.ts @@ -115,30 +134,22 @@ - - - AABB.ts - - - + + + QuadTree.ts + + + + LinkedList.ts + + + + Motion.ts + Body.ts - - Circle.ts - - - - - Fixture.ts - - - IPhysicsBody.ts - - - IPhysicsShape.ts - PhysicsManager.ts @@ -224,12 +235,6 @@ Device.ts - - LinkedList.ts - - - QuadTree.ts - RandomDataGenerator.ts @@ -246,8 +251,6 @@ - - @@ -362,7 +365,6 @@ - diff --git a/Phaser/components/Tile.ts b/Phaser/components/Tile.ts index ab7f955b..d7c4cb88 100644 --- a/Phaser/components/Tile.ts +++ b/Phaser/components/Tile.ts @@ -27,7 +27,7 @@ module Phaser { this.width = width; this.height = height; - this.allowCollisions = Collision.NONE; + this.allowCollisions = Types.NONE; } @@ -144,7 +144,7 @@ module Phaser { this.allowCollisions = collision; - if (collision & Collision.ANY) + if (collision & Types.ANY) { this.collideLeft = true; this.collideRight = true; @@ -153,22 +153,22 @@ module Phaser { return; } - if (collision & Collision.LEFT || collision & Collision.WALL) + if (collision & Types.LEFT || collision & Types.WALL) { this.collideLeft = true; } - if (collision & Collision.RIGHT || collision & Collision.WALL) + if (collision & Types.RIGHT || collision & Types.WALL) { this.collideRight = true; } - if (collision & Collision.UP || collision & Collision.CEILING) + if (collision & Types.UP || collision & Types.CEILING) { this.collideUp = true; } - if (collision & Collision.DOWN || collision & Collision.CEILING) + if (collision & Types.DOWN || collision & Types.CEILING) { this.collideDown = true; } @@ -180,7 +180,7 @@ module Phaser { */ public resetCollision() { - this.allowCollisions = Collision.NONE; + this.allowCollisions = Types.NONE; this.collideLeft = false; this.collideRight = false; this.collideUp = false; diff --git a/Phaser/components/TilemapLayer.ts b/Phaser/components/TilemapLayer.ts index 17e954ad..3183cda7 100644 --- a/Phaser/components/TilemapLayer.ts +++ b/Phaser/components/TilemapLayer.ts @@ -356,30 +356,30 @@ module Phaser { * @param object {GameObject} Tiles you want to get that overlaps this. * @return {array} Array with tiles informations. (Each contains x, y and the tile.) */ - public getTileOverlaps(object: IGameObject) { + public getTileOverlaps(object: Sprite) { // 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) + if (object.body.bounds.x < 0 || object.body.bounds.x > this.widthInPixels || object.body.bounds.y < 0 || object.body.bounds.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; + this._tempTileX = this._game.math.snapToFloor(object.body.bounds.x, this.tileWidth) / this.tileWidth; + this._tempTileY = this._game.math.snapToFloor(object.body.bounds.y, this.tileHeight) / this.tileHeight; + this._tempTileW = (this._game.math.snapToCeil(object.body.bounds.width, this.tileWidth) + this.tileWidth) / this.tileWidth; + this._tempTileH = (this._game.math.snapToCeil(object.body.bounds.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; + Phaser.Physics.PhysicsManager.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) + if (this._game.world.physics.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 }); } @@ -428,7 +428,7 @@ module Phaser { 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) + if (this.mapData[ty] && this.mapData[ty][tx] && this._parent.tiles[this.mapData[ty][tx]].allowCollisions != Types.NONE) { this._tempTileBlock.push({ x: tx, y: ty, tile: this._parent.tiles[this.mapData[ty][tx]] }); } diff --git a/Phaser/components/sprite/CollisionMask.ts b/Phaser/components/sprite/CollisionMask.ts deleted file mode 100644 index f0186ae0..00000000 --- a/Phaser/components/sprite/CollisionMask.ts +++ /dev/null @@ -1,501 +0,0 @@ -/// - -/** -* Phaser - CollisionMask -*/ - -module Phaser { - - export class CollisionMask { - - /** - * 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. - */ - constructor(game: Game, parent: GameObject, x: number, y: number, width: number, height: number) { - - 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 MicroPoint(0, 0); - this.last = new MicroPoint(0, 0); - - this._ref = this.quad; - - return this; - - } - - private _game; - private _parent; - - // An internal reference to the active collision shape - private _ref; - - /** - * Geom type of this sprite. (available: QUAD, POINT, CIRCLE, LINE, RECTANGLE, POLYGON) - * @type {number} - */ - public type: number = 0; - - /** - * Quad (a smaller version of Rectangle). - * @type {number} - */ - public static QUAD: number = 0; - - /** - * Point. - * @type {number} - */ - public static POINT: number = 1; - - /** - * Circle. - * @type {number} - */ - public static CIRCLE: number = 2; - - /** - * Line. - * @type {number} - */ - public static LINE: number = 3; - - /** - * Rectangle. - * @type {number} - */ - public static RECTANGLE: number = 4; - - /** - * Polygon. - * @type {number} - */ - public static POLYGON: number = 5; - - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public quad: Quad; - - /** - * Point shape container. A Point instance. - * @type {Point} - */ - public point: Point; - - /** - * Circle shape container. A Circle instance. - * @type {Circle} - */ - public circle: Circle; - - /** - * Line shape container. A Line instance. - * @type {Line} - */ - public line: Line; - - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public rect: Rectangle; - - /** - * A value from the top-left of the GameObject frame that this collisionMask is offset to. - * If the CollisionMask is a Quad/Rectangle the offset relates to the top-left of that Quad. - * If the CollisionMask is a Circle the offset relates to the center of the circle. - * @type {MicroPoint} - */ - public offset: MicroPoint; - - /** - * The previous x/y coordinates of the CollisionMask, used for hull calculations - * @type {MicroPoint} - */ - public last: MicroPoint; - - /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {CollisionMask} This - */ - createCircle(diameter: number): CollisionMask { - - this.type = CollisionMask.CIRCLE; - this.circle = new Circle(this.last.x, this.last.y, diameter); - this._ref = this.circle; - - return this; - - } - - /** - * Pre-update is called right before update() on each object in the game loop. - */ - public preUpdate() { - - this.last.x = this.x; - this.last.y = this.y; - - } - - public update() { - - this._ref.x = this._parent.x + this.offset.x; - this._ref.y = this._parent.y + this.offset.y; - - } - - /** - * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. - * @param camera {Camera} Camera the bound will be rendered to. - * @param cameraOffsetX {number} X offset of bound to the camera. - * @param cameraOffsetY {number} Y offset of bound to the camera. - */ - public render(camera:Camera, cameraOffsetX:number, cameraOffsetY:number) { - - var _dx = cameraOffsetX + (this.x - camera.worldView.x); - var _dy = cameraOffsetY + (this.y - camera.worldView.y); - - this._parent.context.fillStyle = this._parent.renderDebugColor; - - if (this.type == CollisionMask.QUAD) - { - this._parent.context.fillRect(_dx, _dy, this.width, this.height); - } - else if (this.type == CollisionMask.CIRCLE) - { - this._parent.context.beginPath(); - this._parent.context.arc(_dx, _dy, this.circle.radius, 0, Math.PI * 2); - this._parent.context.fill(); - this._parent.context.closePath(); - } - - } - - /** - * Destroy all objects and references belonging to this CollisionMask - */ - public destroy() { - - 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; - - } - - public intersectsRaw(left: number, right: number, top: number, bottom: number): bool { - -//if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) - - return true; - - } - - public intersectsVector(vector: Phaser.Vector2): bool { - - if (this.type == CollisionMask.QUAD) - { - return this.quad.contains(vector.x, vector.y); - } - - } - - /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - public intersects(source: CollisionMask): bool { - - // 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 Collision.circleToCircle(this.circle, source.circle).result; - } - - // Circle vs. Rect - if (this.type == CollisionMask.CIRCLE && source.type == CollisionMask.RECTANGLE) - { - return Collision.circleToRectangle(this.circle, source.rect).result; - } - - // Circle vs. Point - if (this.type == CollisionMask.CIRCLE && source.type == CollisionMask.POINT) - { - return Collision.circleContainsPoint(this.circle, source.point).result; - } - - // Circle vs. Line - if (this.type == CollisionMask.CIRCLE && source.type == CollisionMask.LINE) - { - return Collision.lineToCircle(source.line, this.circle).result; - } - - // Rect vs. Rect - if (this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.RECTANGLE) - { - return Collision.rectangleToRectangle(this.rect, source.rect).result; - } - - // Rect vs. Circle - if (this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.CIRCLE) - { - return Collision.circleToRectangle(source.circle, this.rect).result; - } - - // Rect vs. Point - if (this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.POINT) - { - return Collision.pointToRectangle(source.point, this.rect).result; - } - - // Rect vs. Line - if (this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.LINE) - { - return 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 Collision.circleContainsPoint(source.circle, this.point).result; - } - - // Point vs. Rect - if (this.type == CollisionMask.POINT && source.type == CollisionMask.RECTANGLE) - { - return 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 Collision.lineSegmentToLineSegment(this.line, source.line).result; - } - - // Line vs. Circle - if (this.type == CollisionMask.LINE && source.type == CollisionMask.CIRCLE) - { - return Collision.lineToCircle(this.line, source.circle).result; - } - - // Line vs. Rect - if (this.type == CollisionMask.LINE && source.type == CollisionMask.RECTANGLE) - { - return 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; - - } - - public checkHullIntersection(mask: CollisionMask): bool { - - if ((this.hullX + this.hullWidth > mask.hullX) && (this.hullX < mask.hullX + mask.width) && (this.hullY + this.hullHeight > mask.hullY) && (this.hullY < mask.hullY + mask.hullHeight)) - { - return true; - } - else - { - return false; - } - - } - - public get hullWidth(): number { - - if (this.deltaX > 0) - { - return this.width + this.deltaX; - } - else - { - return this.width - this.deltaX; - } - - } - - public get hullHeight(): number { - - if (this.deltaY > 0) - { - return this.height + this.deltaY; - } - else - { - return this.height - this.deltaY; - } - - } - - public get hullX(): number { - - if (this.x < this.last.x) - { - return this.x; - } - else - { - return this.last.x; - } - - } - - public get hullY(): number { - - if (this.y < this.last.y) - { - return this.y; - } - else - { - return this.last.y; - } - - } - - public get deltaXAbs(): number { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - } - - public get deltaYAbs(): number { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - } - - public get deltaX(): number { - return this.x - this.last.x; - } - - public get deltaY(): number { - return this.y - this.last.y; - } - - public get x(): number { - return this._ref.x; - //return this.quad.x; - } - - public set x(value: number) { - this._ref.x = value; - //this.quad.x = value; - } - - public get y(): number { - return this._ref.y; - //return this.quad.y; - } - - public set y(value: number) { - this._ref.y = value; - //this.quad.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.quad.width = value; - this._ref.width = value; - } - - public set height(value:number) { - //this.quad.height = value; - this._ref.height = value; - } - - public get width(): number { - //return this.quad.width; - return this._ref.width; - } - - public get height(): number { - //return this.quad.height; - return this._ref.height; - } - - public get left(): number { - return this.x; - } - - public get right(): number { - return this.x + this.width; - } - - public get top(): number { - return this.y; - } - - public get bottom(): number { - return this.y + this.height; - } - - public get halfWidth(): number { - return this.width / 2; - } - - public get halfHeight(): number { - return this.height / 2; - } - - } - -} \ No newline at end of file diff --git a/Phaser/components/sprite/Events.ts b/Phaser/components/sprite/Events.ts new file mode 100644 index 00000000..30e446ba --- /dev/null +++ b/Phaser/components/sprite/Events.ts @@ -0,0 +1,39 @@ +/// +/// +/// + +/** +* Phaser - Components - Events +* +* +*/ + +module Phaser.Components { + + export class Events { + + constructor(parent: Sprite, key?: string = '') { + + this._game = parent.game; + this._sprite = parent; + + } + + /** + * + */ + private _game: Game; + + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ + private _sprite: Sprite; + + public onInputOver: Phaser.Signal; + public onInputOut: Phaser.Signal; + public onInputDown: Phaser.Signal; + public onInputUp: Phaser.Signal; + + } + +} \ No newline at end of file diff --git a/Phaser/components/sprite/Input.ts b/Phaser/components/sprite/Input.ts deleted file mode 100644 index 75a23b04..00000000 --- a/Phaser/components/sprite/Input.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** -* 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 deleted file mode 100644 index 0cb8ff7a..00000000 --- a/Phaser/components/sprite/Physics.ts +++ /dev/null @@ -1,108 +0,0 @@ -/// -/// -/// -/// -/// -/// -/// - -/** -* Phaser - Components - Physics -*/ - -module Phaser.Components { - - export class Physics implements Phaser.Physics.IPhysicsBody { - - constructor(parent: Sprite) { - - this.game = parent.game; - this._sprite = parent; - - this.gravity = Vec2Utils.clone(this.game.world.physics.gravity); - this.drag = Vec2Utils.clone(this.game.world.physics.drag); - this.bounce = Vec2Utils.clone(this.game.world.physics.bounce); - this.friction = Vec2Utils.clone(this.game.world.physics.friction); - - this.velocity = new Vec2; - this.acceleration = new Vec2; - - this.touching = Phaser.Types.NONE; - this.wasTouching = Phaser.Types.NONE; - this.allowCollisions = Phaser.Types.ANY; - - this.shape = this.game.world.physics.add(new Phaser.Physics.AABB(this.game, this._sprite, this._sprite.x, this._sprite.y, this._sprite.width, this._sprite.height)); - - } - - private _sprite: Sprite; - - public game: Game; - public shape: Phaser.Physics.IPhysicsShape; - - /** - * Whether this object will be moved by impacts with other objects or not. - * @type {boolean} - */ - public immovable: bool = false; - - /** - * Set this to false if you want to skip the automatic movement stuff - * @type {boolean} - */ - public moves: bool = true; - - public gravity: Vec2; - public drag: Vec2; - public bounce: Vec2; - public friction: Vec2; - public velocity: Vec2; - public acceleration: Vec2; - - public touching: number; - public allowCollisions: number; - public wasTouching: number; - public mass: number = 1; - - public setCircle(diameter: number) { - - // Here is the stuff I want to remove - this.game.world.physics.remove(this.shape); - this.shape = this.game.world.physics.add(new Phaser.Physics.Circle(this.game, this._sprite, this._sprite.x, this._sprite.y, diameter)); - this._sprite.physics.shape.physics = this; - - } - - /** - * Internal function for updating the position and speed of this object. - */ - public update() { - - // if this is all it does maybe move elsewhere? Sprite postUpdate? - if (this.moves && this.shape) - { - this._sprite.x = (this.shape.position.x - this.shape.bounds.halfWidth) - this.shape.offset.x; - this._sprite.y = (this.shape.position.y - this.shape.bounds.halfHeight) - this.shape.offset.y; - } - } - - /** - * 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._sprite.texture.context.fillStyle = color; - this._sprite.texture.context.fillText('Sprite: (' + this._sprite.frameBounds.width + ' x ' + this._sprite.frameBounds.height + ')', x, y); - //this._sprite.texture.context.fillText('x: ' + this._sprite.frameBounds.x.toFixed(1) + ' y: ' + this._sprite.frameBounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('x: ' + this.shape.bounds.x.toFixed(1) + ' y: ' + this.shape.bounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); - this._sprite.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); - - } - - } - -} \ No newline at end of file diff --git a/Phaser/components/sprite/Properties.ts b/Phaser/components/sprite/Properties.ts deleted file mode 100644 index 3171afe9..00000000 --- a/Phaser/components/sprite/Properties.ts +++ /dev/null @@ -1,36 +0,0 @@ -/** -* 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/gameobjects/Emitter.ts b/Phaser/gameobjects/Emitter.ts index 1aa5d2b1..6e4a3d3f 100644 --- a/Phaser/gameobjects/Emitter.ts +++ b/Phaser/gameobjects/Emitter.ts @@ -1,5 +1,7 @@ /// -/// +/// +/// +/// /** * Phaser - Emitter @@ -29,13 +31,13 @@ module Phaser { this.y = y; this.width = 0; this.height = 0; - this.minParticleSpeed = new MicroPoint(-100, -100); - this.maxParticleSpeed = new MicroPoint(100, 100); + this.minParticleSpeed = new Vec2(-100, -100); + this.maxParticleSpeed = new Vec2(100, 100); this.minRotation = -360; this.maxRotation = 360; this.gravity = 0; this.particleClass = null; - this.particleDrag = new MicroPoint(); + this.particleDrag = new Vec2(); this.frequency = 0.1; this.lifespan = 3; this.bounce = 0; @@ -43,7 +45,6 @@ module Phaser { this._counter = 0; this._explode = true; this.on = false; - this._point = new MicroPoint(); } @@ -67,22 +68,27 @@ module Phaser { */ public height: number; + /** + * + */ + public alive: bool; + /** * The minimum possible velocity of a particle. * The default value is (-100,-100). */ - public minParticleSpeed: MicroPoint; + public minParticleSpeed: Vec2; /** * The maximum possible velocity of a particle. * The default value is (100,100). */ - public maxParticleSpeed: MicroPoint; + public maxParticleSpeed: Vec2; /** * The X and Y drag component of particles launched from the emitter. */ - public particleDrag: MicroPoint; + public particleDrag: Vec2; /** * The minimum possible angular velocity of a particle. The default value is -360. @@ -152,7 +158,7 @@ module Phaser { /** * Internal point object, handy for reusing for memory mgmt purposes. */ - private _point: MicroPoint; + private _point: Vec2; /** * Clean up memory. @@ -185,7 +191,7 @@ module Phaser { /* if(Multiple) { - var sprite:Sprite = new Sprite(this._game); + var sprite:Sprite = new Sprite(this.game); sprite.loadGraphic(Graphics,true); totalFrames = sprite.frames; sprite.destroy(); @@ -200,17 +206,17 @@ module Phaser { { if (this.particleClass == null) { - particle = new Particle(this._game); + particle = new Particle(this.game); } else { - particle = new this.particleClass(this._game); + particle = new this.particleClass(this.game); } if (multiple) { /* - randomFrame = this._game.math.random()*totalFrames; + randomFrame = this.game.math.random()*totalFrames; if(BakedRotations > 0) particle.loadRotatedGraphic(Graphics,BakedRotations,randomFrame); else @@ -231,21 +237,21 @@ module Phaser { if (graphics) { - particle.loadGraphic(graphics); + particle.texture.loadImage(graphics); } } if (collide > 0) { - particle.allowCollisions = Collision.ANY; + particle.body.allowCollisions = Types.ANY; + particle.body.type = Types.BODY_DYNAMIC; particle.width *= collide; particle.height *= collide; - //particle.centerOffsets(); } else { - particle.allowCollisions = Collision.NONE; + particle.body.allowCollisions = Types.NONE; } particle.exists = false; @@ -287,7 +293,7 @@ module Phaser { } else { - this._timer += this._game.time.elapsed; + this._timer += this.game.time.elapsed; while ((this.frequency > 0) && (this._timer > this.frequency) && this.on) { @@ -311,11 +317,18 @@ module Phaser { * Call this function to turn off all the particles and the emitter. */ public kill() { - this.on = false; + this.alive = false; + this.exists = false; + } - super.kill(); - + /** + * 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; } /** @@ -351,46 +364,46 @@ module Phaser { var particle: Particle = this.recycle(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.body.bounce.setTo(this.bounce, this.bounce); + SpriteUtils.reset(particle, 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); + particle.body.velocity.x = this.minParticleSpeed.x + this.game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x); } else { - particle.velocity.x = this.minParticleSpeed.x; + particle.body.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); + particle.body.velocity.y = this.minParticleSpeed.y + this.game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y); } else { - particle.velocity.y = this.minParticleSpeed.y; + particle.body.velocity.y = this.minParticleSpeed.y; } - particle.acceleration.y = this.gravity; + particle.body.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); + particle.body.angularVelocity = this.minRotation + this.game.math.random() * (this.maxRotation - this.minRotation); } else { - particle.angularVelocity = this.minRotation; + particle.body.angularVelocity = this.minRotation; } - if (particle.angularVelocity != 0) + if (particle.body.angularVelocity != 0) { - particle.angle = this._game.math.random() * 360 - 180; + particle.angle = this.game.math.random() * 360 - 180; } - particle.drag.x = this.particleDrag.x; - particle.drag.y = this.particleDrag.y; + particle.body.drag.x = this.particleDrag.x; + particle.body.drag.y = this.particleDrag.y; particle.onEmit(); } @@ -444,10 +457,9 @@ module Phaser { * * @param Object {object} The Object that you want to sync up with. */ - public at(object) { - object.getMidpoint(this._point); - this.x = this._point.x - (this.width >> 1); - this.y = this._point.y - (this.height >> 1); + public at(object: Sprite) { + this.x = object.body.bounds.halfWidth - (this.width >> 1); + this.y = object.body.bounds.halfHeight - (this.height >> 1); } } diff --git a/Phaser/gameobjects/GameObjectFactory.ts b/Phaser/gameobjects/GameObjectFactory.ts index 008d390d..d77d6b1b 100644 --- a/Phaser/gameobjects/GameObjectFactory.ts +++ b/Phaser/gameobjects/GameObjectFactory.ts @@ -1,6 +1,11 @@ /// /// -/// +/// +/// +/// +/// +/// +/// /** * Phaser - GameObjectFactory @@ -97,9 +102,9 @@ module Phaser { * * @return {Particle} The newly created particle object. */ - //public particle(): Particle { - // return new Particle(this._game); - //} + public particle(): Particle { + return new Particle(this._game); + } /** * Create a new Emitter. @@ -109,9 +114,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.group.add(new Emitter(this._game, 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. @@ -138,9 +143,9 @@ module Phaser { * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { - // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - //} + public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { + return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + } /** * Create a tween object for a specific object. @@ -181,9 +186,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. @@ -203,9 +208,9 @@ module Phaser { * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - //public existingTilemap(tilemap: Tilemap): Tilemap { - // return this._world.group.add(tilemap); - //} + public existingTilemap(tilemap: Tilemap): Tilemap { + return this._world.group.add(tilemap); + } /** * Add an existing Tween to the current world. diff --git a/Phaser/gameobjects/GeomSprite.ts b/Phaser/gameobjects/GeomSprite.ts deleted file mode 100644 index 81ac326e..00000000 --- a/Phaser/gameobjects/GeomSprite.ts +++ /dev/null @@ -1,645 +0,0 @@ -/// -/// -/// - -/** -* 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. -*/ - -module Phaser { - - export class GeomSprite extends Sprite { - - /** - * 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. - */ - constructor(game: Game, x?: number = 0, y?: number = 0) { - - super(game, x, y); - - this.type = GeomSprite.UNASSIGNED; - - return this; - - } - - // local rendering related temp vars to help avoid gc spikes - private _dx: number = 0; - private _dy: number = 0; - private _dw: number = 0; - private _dh: number = 0; - - /** - * Geom type of this sprite. (available: UNASSIGNED, CIRCLE, LINE, POINT, RECTANGLE) - * @type {number} - */ - public type: number = 0; - - /** - * Not completely set yet. (the default type) - */ - public static UNASSIGNED: number = 0; - - /** - * Circle. - * @type {number} - */ - public static CIRCLE: number = 1; - - /** - * Line. - * @type {number} - */ - public static LINE: number = 2; - - /** - * Point. - * @type {number} - */ - public static POINT: number = 3; - - /** - * Rectangle. - * @type {number} - */ - public static RECTANGLE: number = 4; - - /** - * Polygon. - * @type {number} - */ - public static POLYGON: number = 5; - - /** - * Circle shape container. A Circle instance. - * @type {Circle} - */ - public circle: Circle; - - /** - * Line shape container. A Line instance. - * @type {Line} - */ - public line: Line; - - /** - * Point shape container. A Point instance. - * @type {Point} - */ - public point: Point; - - /** - * Rectangle shape container. A Rectangle instance. - * @type {Rectangle} - */ - public rect: Rectangle; - - /** - * Polygon shape container. A Polygon instance. - * @type {Polygon} - */ - public polygon: Polygon; - - /** - * Render outline of this sprite or not. (default is true) - * @type {boolean} - */ - public renderOutline: bool = true; - - /** - * Fill the shape or not. (default is true) - * @type {boolean} - */ - public renderFill: bool = true; - - /** - * Width of outline. (default is 1) - * @type {number} - */ - public lineWidth: number = 1; - - /** - * Width of outline. (default is 1) - * @type {number} - */ - public lineColor: string = '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 - */ - public fillColor: string = 'rgb(0,100,0)'; - - /** - * 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. - */ - loadCircle(circle:Circle): GeomSprite { - - this.refresh(); - this.circle = circle; - this.type = GeomSprite.CIRCLE; - return this; - - } - - /** - * 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. - */ - loadLine(line:Line): GeomSprite { - - this.refresh(); - this.line = line; - this.type = GeomSprite.LINE; - return this; - - } - - /** - * 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. - */ - loadPoint(point:Point): GeomSprite { - - this.refresh(); - this.point = point; - this.type = GeomSprite.POINT; - return this; - - } - - /** - * 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. - */ - loadRectangle(rect:Rectangle): GeomSprite { - - this.refresh(); - this.rect = rect; - this.type = GeomSprite.RECTANGLE; - return this; - - } - - /** - * Create a circle shape with specific diameter. - * @param diameter {number} Diameter of the circle. - * @return {GeomSprite} GeomSprite instance itself. - */ - createCircle(diameter: number): GeomSprite { - - this.refresh(); - this.circle = new Circle(this.x, this.y, diameter); - this.type = GeomSprite.CIRCLE; - this.frameBounds.setTo(this.circle.x - this.circle.radius, this.circle.y - this.circle.radius, this.circle.diameter, this.circle.diameter); - return this; - - } - - /** - * 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. - */ - createLine(x: number, y: number): GeomSprite { - - this.refresh(); - this.line = new Line(this.x, this.y, x, y); - this.type = GeomSprite.LINE; - this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); - return this; - - } - - /** - * Create a point shape at spriter's position. - * @return {GeomSprite} GeomSprite instance itself. - */ - createPoint(): GeomSprite { - - this.refresh(); - this.point = new Point(this.x, this.y); - this.type = GeomSprite.POINT; - this.frameBounds.width = 1; - this.frameBounds.height = 1; - return this; - - } - - /** - * 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. - */ - createRectangle(width: number, height: number): GeomSprite { - - this.refresh(); - this.rect = new Rectangle(this.x, this.y, width, height); - this.type = GeomSprite.RECTANGLE; - this.frameBounds.copyFrom(this.rect); - return this; - - } - - /** - * Create a polygon object - * @param width {Number} Width of the rectangle - * @param height {Number} Height of the rectangle - * @return {GeomSprite} GeomSprite instance. - */ - createPolygon(points?: Vec2[] = []): GeomSprite { - - //this.refresh(); - //this.polygon = new Polygon(new Vec2(this.x, this.y), points); - //this.type = GeomSprite.POLYGON; - //this.frameBounds.copyFrom(this.rect); - return this; - - } - - /** - * Destroy all geom shapes of this sprite. - */ - refresh() { - - this.circle = null; - this.line = null; - this.point = null; - this.rect = null; - - } - - /** - * Update bounds. - */ - update() { - - // Update bounds and position? - if (this.type == GeomSprite.UNASSIGNED) - { - return; - } - else if (this.type == GeomSprite.CIRCLE) - { - this.circle.x = this.x; - this.circle.y = this.y; - this.frameBounds.width = this.circle.diameter; - this.frameBounds.height = this.circle.diameter; - } - else if (this.type == GeomSprite.LINE) - { - this.line.x1 = this.x; - this.line.y1 = this.y; - this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); - } - else if (this.type == GeomSprite.POINT) - { - this.point.x = this.x; - this.point.y = this.y; - } - else if (this.type == GeomSprite.RECTANGLE) - { - this.rect.x = this.x; - this.rect.y = this.y; - this.frameBounds.copyFrom(this.rect); - } - - } - - /** - * Check whether this object is visible in a specific camera rectangle. - * @param camera {Rectangle} The rectangle you want to check. - * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. - */ - /* - public inCamera(camera: Rectangle): bool { - - 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); - } - - } - */ - - /** - * 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.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) - { - var globalAlpha = this.context.globalAlpha; - this.context.globalAlpha = this.alpha; - } - - this._dx = cameraOffsetX + (this.frameBounds.x - camera.worldView.x); - this._dy = cameraOffsetY + (this.frameBounds.y - camera.worldView.y); - this._dw = this.frameBounds.width * this.scale.x; - this._dh = this.frameBounds.height * this.scale.y; - - // Apply camera difference - if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) - { - this._dx -= (camera.worldView.x * this.scrollFactor.x); - this._dy -= (camera.worldView.y * this.scrollFactor.y); - } - - // Rotation is disabled for now as I don't want it to be misleading re: collision - /* - if (this.angle !== 0) - { - this.context.save(); - this.context.translate(this._dx + (this._dw / 2) - this.origin.x, this._dy + (this._dh / 2) - this.origin.y); - this.context.rotate(this.angle * (Math.PI / 180)); - this._dx = -(this._dw / 2); - this._dy = -(this._dh / 2); - } - */ - - this._dx = Math.round(this._dx); - this._dy = Math.round(this._dy); - this._dw = Math.round(this._dw); - this._dh = Math.round(this._dh); - - this._game.stage.saveCanvasValues(); - - // Debug - //this.context.fillStyle = 'rgba(255,0,0,0.5)'; - //this.context.fillRect(this.frameBounds.x, this.frameBounds.y, this.frameBounds.width, this.frameBounds.height); - - this.context.lineWidth = this.lineWidth; - this.context.strokeStyle = this.lineColor; - this.context.fillStyle = this.fillColor; - - if (this._game.stage.fillStyle !== this.fillColor) - { - } - - // Primitive Renderer - if (this.type == GeomSprite.CIRCLE) - { - this.context.beginPath(); - this.context.arc(this._dx, this._dy, this.circle.radius, 0, Math.PI * 2); - - if (this.renderOutline) - { - this.context.stroke(); - } - - if (this.renderFill) - { - this.context.fill(); - } - - this.context.closePath(); - } - else if (this.type == GeomSprite.LINE) - { - this.context.beginPath(); - this.context.moveTo(this._dx, this._dy); - this.context.lineTo(this.line.x2, this.line.y2); - this.context.stroke(); - this.context.closePath(); - } - else if (this.type == GeomSprite.POINT) - { - this.context.fillRect(this._dx, this._dy, 2, 2); - } - else if (this.type == GeomSprite.RECTANGLE) - { - // We can use the faster fillRect if we don't need the outline - if (this.renderOutline == false) - { - this.context.fillRect(this._dx, this._dy, this.rect.width, this.rect.height); - } - else - { - this.context.beginPath(); - this.context.rect(this._dx, this._dy, this.rect.width, this.rect.height); - this.context.stroke(); - - if (this.renderFill) - { - this.context.fill(); - } - - this.context.closePath(); - } - - // And now the edge points - this.context.fillStyle = 'rgb(255,255,255)'; - //this.renderPoint(this.rect.topLeft, this._dx, this._dy, 2); - //this.renderPoint(this.rect.topCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.topRight, this._dx, this._dy, 2); - //this.renderPoint(this.rect.leftCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.center, this._dx, this._dy, 2); - //this.renderPoint(this.rect.rightCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomLeft, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomCenter, this._dx, this._dy, 2); - //this.renderPoint(this.rect.bottomRight, this._dx, this._dy, 2); - this.renderPoint(this.rect.topLeft, 0, 0, 2); - this.renderPoint(this.rect.topCenter, 0, 0, 2); - this.renderPoint(this.rect.topRight, 0, 0, 2); - this.renderPoint(this.rect.leftCenter, 0, 0, 2); - this.renderPoint(this.rect.center, 0, 0, 2); - this.renderPoint(this.rect.rightCenter, 0, 0, 2); - this.renderPoint(this.rect.bottomLeft, 0, 0, 2); - this.renderPoint(this.rect.bottomCenter, 0, 0, 2); - this.renderPoint(this.rect.bottomRight, 0, 0, 2); - - } - - this._game.stage.restoreCanvasValues(); - - if (this.rotation !== 0) - { - this.context.translate(0, 0); - this.context.restore(); - } - - if (globalAlpha > -1) - { - this.context.globalAlpha = globalAlpha; - } - - return true; - - } - - /** - * Render a point of geometry. - * @param point {Point} Position of the point. - * @param offsetX {number} X offset to its position. - * @param offsetY {number} Y offset to its position. - * @param [size] {number} point size. - */ - public renderPoint(point, offsetX?: number = 0, offsetY?: number = 0, size?: number = 1) { - - this.context.fillRect(offsetX + point.x, offsetY + point.y, size, size); - - } - - /** - * Render debug infos. (this method does not work now) - * @param x {number} X position of the debug info to be rendered. - * @param y {number} Y position of the debug info to be rendered. - * @param [color] {number} color of the debug info to be rendered. (format is css color string) - */ - public renderDebugInfo(x: number, y: number, color?: string = '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); - - } - - /** - * Gives a basic boolean response to a geometric collision. - * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. - * @param source {GeomSprite} Sprite you want to check. - * @return {boolean} Whether they overlaps or not. - */ - public collide(source: GeomSprite): bool { - - // Circle vs. Circle - if (this.type == GeomSprite.CIRCLE && source.type == GeomSprite.CIRCLE) - { - return Collision.circleToCircle(this.circle, source.circle).result; - } - - // Circle vs. Rect - if (this.type == GeomSprite.CIRCLE && source.type == GeomSprite.RECTANGLE) - { - return Collision.circleToRectangle(this.circle, source.rect).result; - } - - // Circle vs. Point - if (this.type == GeomSprite.CIRCLE && source.type == GeomSprite.POINT) - { - return Collision.circleContainsPoint(this.circle, source.point).result; - } - - // Circle vs. Line - if (this.type == GeomSprite.CIRCLE && source.type == GeomSprite.LINE) - { - return Collision.lineToCircle(source.line, this.circle).result; - } - - // Rect vs. Rect - if (this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.RECTANGLE) - { - return Collision.rectangleToRectangle(this.rect, source.rect).result; - } - - // Rect vs. Circle - if (this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.CIRCLE) - { - return Collision.circleToRectangle(source.circle, this.rect).result; - } - - // Rect vs. Point - if (this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.POINT) - { - return Collision.pointToRectangle(source.point, this.rect).result; - } - - // Rect vs. Line - if (this.type == GeomSprite.RECTANGLE && source.type == GeomSprite.LINE) - { - return Collision.lineToRectangle(source.line, this.rect).result; - } - - // Point vs. Point - if (this.type == GeomSprite.POINT && source.type == GeomSprite.POINT) - { - return this.point.equals(source.point); - } - - // Point vs. Circle - if (this.type == GeomSprite.POINT && source.type == GeomSprite.CIRCLE) - { - return Collision.circleContainsPoint(source.circle, this.point).result; - } - - // Point vs. Rect - if (this.type == GeomSprite.POINT && source.type == GeomSprite.RECTANGLE) - { - return Collision.pointToRectangle(this.point, source.rect).result; - } - - // Point vs. Line - if (this.type == GeomSprite.POINT && source.type == GeomSprite.LINE) - { - return source.line.isPointOnLine(this.point.x, this.point.y); - } - - // Line vs. Line - if (this.type == GeomSprite.LINE && source.type == GeomSprite.LINE) - { - return Collision.lineSegmentToLineSegment(this.line, source.line).result; - } - - // Line vs. Circle - if (this.type == GeomSprite.LINE && source.type == GeomSprite.CIRCLE) - { - return Collision.lineToCircle(this.line, source.circle).result; - } - - // Line vs. Rect - if (this.type == GeomSprite.LINE && source.type == GeomSprite.RECTANGLE) - { - return Collision.lineSegmentToRectangle(this.line, source.rect).result; - } - - // Line vs. Point - if (this.type == GeomSprite.LINE && source.type == GeomSprite.POINT) - { - return this.line.isPointOnLine(source.point.x, source.point.y); - } - - return false; - - } - - } - -} \ No newline at end of file diff --git a/Phaser/gameobjects/OldSprite.ts b/Phaser/gameobjects/OldSprite.ts deleted file mode 100644 index 1e28f513..00000000 --- a/Phaser/gameobjects/OldSprite.ts +++ /dev/null @@ -1,355 +0,0 @@ -/// -/// -/// -/// - -/** -* 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.ts b/Phaser/gameobjects/Particle.ts index c781f657..341c7e79 100644 --- a/Phaser/gameobjects/Particle.ts +++ b/Phaser/gameobjects/Particle.ts @@ -51,7 +51,7 @@ module Phaser { return; } - this.lifespan -= this._game.time.elapsed; + this.lifespan -= this.game.time.elapsed; if (this.lifespan <= 0) { @@ -59,39 +59,39 @@ module Phaser { } //simpler bounce/spin behavior for now - if (this.touching) + if (this.body.touching) { - if (this.angularVelocity != 0) + if (this.body.angularVelocity != 0) { - this.angularVelocity = -this.angularVelocity; + this.body.angularVelocity = -this.body.angularVelocity; } } - if (this.acceleration.y > 0) //special behavior for particles with gravity + if (this.body.acceleration.y > 0) //special behavior for particles with gravity { - if (this.touching & Collision.FLOOR) + if (this.body.touching & Types.FLOOR) { - this.drag.x = this.friction; + this.body.drag.x = this.friction; - if (!(this.wasTouching & Collision.FLOOR)) + if (!(this.body.wasTouching & Types.FLOOR)) { - if (this.velocity.y < -this.elasticity * 10) + if (this.body.velocity.y < -this.body.bounce.y * 10) { - if (this.angularVelocity != 0) + if (this.body.angularVelocity != 0) { - this.angularVelocity *= -this.elasticity; + this.body.angularVelocity *= -this.body.bounce.y; } } else { - this.velocity.y = 0; - this.angularVelocity = 0; + this.body.velocity.y = 0; + this.body.angularVelocity = 0; } } } else { - this.drag.x = 0; + this.body.drag.x = 0; } } } diff --git a/Phaser/gameobjects/ScrollZone.ts b/Phaser/gameobjects/ScrollZone.ts index 4c84e350..16152d0f 100644 --- a/Phaser/gameobjects/ScrollZone.ts +++ b/Phaser/gameobjects/ScrollZone.ts @@ -28,11 +28,10 @@ module Phaser { */ constructor(game: Game, key:string, x: number = 0, y: number = 0, width?: number = 0, height?: number = 0) { - super(game, x, y, key, width, height); + super(game, x, y, key); this.type = Phaser.Types.SCROLLZONE; this.render = game.renderer.renderScrollZone; - this.physics.moves = false; this.regions = []; diff --git a/Phaser/gameobjects/Sprite.ts b/Phaser/gameobjects/Sprite.ts index ea0f1d40..83cb55d3 100644 --- a/Phaser/gameobjects/Sprite.ts +++ b/Phaser/gameobjects/Sprite.ts @@ -3,7 +3,6 @@ /// /// /// -/// /// /** @@ -24,7 +23,6 @@ module Phaser { * @param [key] {string} Key of the graphic you want to load for this sprite. * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) */ - //constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null, width?: number = 16, height?: number = 16) { constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null, bodyType?: number = Phaser.Types.BODY_DISABLED) { this.game = game; @@ -46,6 +44,7 @@ module Phaser { this.animations = new Phaser.Components.AnimationManager(this); this.texture = new Phaser.Components.Texture(this, key); + this.cameraBlacklist = []; // Transform related (if we add any more then move to a component) this.origin = new Phaser.Vec2(0, 0); @@ -108,6 +107,12 @@ module Phaser { */ public animations: Phaser.Components.AnimationManager; + /** + * An Array of Cameras to which this GameObject won't render + * @type {Array} + */ + public cameraBlacklist: number[]; + /** * The frame boundary around this Sprite. * For non-animated sprites this matches the loaded texture dimensions. @@ -290,7 +295,7 @@ module Phaser { */ - if (this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.rotation == 0 && this.rotationOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) + if (this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.angle == 0 && this.angleOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) { this.modified = false; } @@ -303,6 +308,27 @@ module Phaser { public destroy() { } + /** + * 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; + } + } } \ No newline at end of file diff --git a/Phaser/gameobjects/Tilemap.ts b/Phaser/gameobjects/Tilemap.ts index 746d7df5..4c2a186f 100644 --- a/Phaser/gameobjects/Tilemap.ts +++ b/Phaser/gameobjects/Tilemap.ts @@ -27,12 +27,17 @@ module Phaser { */ constructor(game: Game, key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0) { - //super(game); + this.game = game; + this.type = Phaser.Types.TILEMAP; - this.isGroup = false; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; this.tiles = []; this.layers = []; + this.cameraBlacklist = []; this.mapFormat = format; @@ -49,18 +54,49 @@ module Phaser { if (this.currentLayer && resizeWorld) { - this._game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); + this.game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); } } private _tempCollisionData; + /** + * Reference to the main game object + */ + public game: Game; + + /** + * The type of game object. + */ + public type: number; + + /** + * Controls if both update and render are called by the core game loop. + */ + public exists: bool; + + /** + * Controls if update() is automatically called by the core game loop. + */ + public active: bool; + + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + public visible: bool; + + /** + * + */ + public alive: bool; + /** * Tilemap data format enum: CSV. * @type {number} */ public static FORMAT_CSV: number = 0; + /** * Tilemap data format enum: Tiled JSON. * @type {number} @@ -72,36 +108,48 @@ module Phaser { * @type {Tile[]} */ public tiles : Tile[]; + /** * Array contains tilemap layer objects of this map. * @type {TilemapLayer[]} */ public layers : TilemapLayer[]; + /** * Current tilemap layer. * @type {TilemapLayer} */ public currentLayer: TilemapLayer; + /** * The tilemap layer for collision. * @type {TilemapLayer} */ public collisionLayer: TilemapLayer; + /** * Tilemap collision callback. * @type {function} */ public collisionCallback = null; + /** * Context for the collision callback called with. */ public collisionCallbackContext; + /** * Format of this tilemap data. Available values: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. * @type {number} */ public mapFormat: number; + /** + * An Array of Cameras to which this GameObject won't render + * @type {Array} + */ + public cameraBlacklist: number[]; + /** * Inherited update method. */ @@ -136,7 +184,7 @@ module Phaser { */ private parseCSV(data: string, key: string, tileWidth: number, tileHeight: number) { - var layer: TilemapLayer = new TilemapLayer(this._game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); + var layer: TilemapLayer = new TilemapLayer(this.game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); // Trim any rogue whitespace from the data data = data.trim(); @@ -179,7 +227,7 @@ module Phaser { for (var i = 0; i < json.layers.length; i++) { - var layer: TilemapLayer = new TilemapLayer(this._game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); + var layer: TilemapLayer = new TilemapLayer(this.game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); layer.alpha = json.layers[i].opacity; layer.visible = json.layers[i].visible; @@ -230,7 +278,7 @@ module Phaser { for (var i = 0; i < qty; i++) { - this.tiles.push(new Tile(this._game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); + this.tiles.push(new Tile(this.game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); } } @@ -266,7 +314,7 @@ module Phaser { * @param separateX {boolean} Enable seprate at x-axis. * @param separateY {boolean} Enable seprate at y-axis. */ - public setCollisionRange(start: number, end: number, collision?:number = Collision.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) { + public setCollisionRange(start: number, end: number, collision?:number = Types.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) { for (var i = start; i < end; i++) { @@ -283,7 +331,7 @@ module Phaser { * @param separateX {boolean} Enable seprate at x-axis. * @param separateY {boolean} Enable seprate at y-axis. */ - public setCollisionByIndex(values:number[], collision?:number = Collision.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) { + public setCollisionByIndex(values:number[], collision?:number = Types.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) { for (var i = 0; i < values.length; i++) { @@ -338,7 +386,7 @@ module Phaser { public getTileFromInputXY(layer?: number = 0):Tile { - return this.tiles[this.layers[layer].getTileFromWorldXY(this._game.input.getWorldX(), this._game.input.getWorldY())]; + return this.tiles[this.layers[layer].getTileFromWorldXY(this.game.input.getWorldX(), this.game.input.getWorldY())]; } @@ -347,7 +395,7 @@ module Phaser { * @param object {GameObject} Tiles you want to get that overlaps this. * @return {array} Array with tiles informations. (Each contains x, y and the tile.) */ - public getTileOverlaps(object: GameObject) { + public getTileOverlaps(object: Sprite) { return this.currentLayer.getTileOverlaps(object); @@ -371,7 +419,7 @@ module Phaser { if (objectOrGroup == null) { - objectOrGroup = this._game.world.group; + objectOrGroup = this.game.world.group; } // Group? @@ -391,9 +439,9 @@ module Phaser { * @param object {GameObject} Target object you want to check. * @return {boolean} Return true if this collides with given object, otherwise return false. */ - public collideGameObject(object: GameObject): bool { + public collideGameObject(object: Sprite): bool { - if (object !== this && object.immovable == false && object.exists == true && object.allowCollisions != Collision.NONE) + if (object.body.type == Types.BODY_DYNAMIC && object.exists == true && object.body.allowCollisions != Types.NONE) { this._tempCollisionData = this.collisionLayer.getTileOverlaps(object); diff --git a/Phaser/math/GameMath.ts b/Phaser/math/GameMath.ts index d41ec49a..7610ae80 100644 --- a/Phaser/math/GameMath.ts +++ b/Phaser/math/GameMath.ts @@ -12,53 +12,51 @@ module Phaser { export class GameMath { constructor(game: Game) { - - this._game = game; - + this.game = game; } - private _game: Game; + public game: Game; - public static PI: number = 3.141592653589793; //number pi - public static PI_2: number = 1.5707963267948965; //PI / 2 OR 90 deg - public static PI_4: number = 0.7853981633974483; //PI / 4 OR 45 deg - public static PI_8: number = 0.39269908169872413; //PI / 8 OR 22.5 deg - public static PI_16: number = 0.19634954084936206; //PI / 16 OR 11.25 deg - public static TWO_PI: number = 6.283185307179586; //2 * PI OR 180 deg - public static THREE_PI_2: number = 4.7123889803846895; //3 * PI_2 OR 270 deg - public static E: number = 2.71828182845905; //number e - public static LN10: number = 2.302585092994046; //ln(10) - public static LN2: number = 0.6931471805599453; //ln(2) - public static LOG10E: number = 0.4342944819032518; //logB10(e) - public static LOG2E: number = 1.442695040888963387; //logB2(e) - public static SQRT1_2: number = 0.7071067811865476; //sqrt( 1 / 2 ) - public static SQRT2: number = 1.4142135623730951; //sqrt( 2 ) - public static DEG_TO_RAD: number = 0.017453292519943294444444444444444; //PI / 180; - public static RAD_TO_DEG: number = 57.295779513082325225835265587527; // 180.0 / PI; + static PI: number = 3.141592653589793; //number pi + static PI_2: number = 1.5707963267948965; //PI / 2 OR 90 deg + static PI_4: number = 0.7853981633974483; //PI / 4 OR 45 deg + static PI_8: number = 0.39269908169872413; //PI / 8 OR 22.5 deg + static PI_16: number = 0.19634954084936206; //PI / 16 OR 11.25 deg + static TWO_PI: number = 6.283185307179586; //2 * PI OR 180 deg + static THREE_PI_2: number = 4.7123889803846895; //3 * PI_2 OR 270 deg + static E: number = 2.71828182845905; //number e + static LN10: number = 2.302585092994046; //ln(10) + static LN2: number = 0.6931471805599453; //ln(2) + static LOG10E: number = 0.4342944819032518; //logB10(e) + static LOG2E: number = 1.442695040888963387; //logB2(e) + static SQRT1_2: number = 0.7071067811865476; //sqrt( 1 / 2 ) + static SQRT2: number = 1.4142135623730951; //sqrt( 2 ) + static DEG_TO_RAD: number = 0.017453292519943294444444444444444; //PI / 180; + static RAD_TO_DEG: number = 57.295779513082325225835265587527; // 180.0 / PI; - public static B_16: number = 65536;//2^16 - public static B_31: number = 2147483648;//2^31 - public static B_32: number = 4294967296;//2^32 - public static B_48: number = 281474976710656;//2^48 - public static B_53: number = 9007199254740992;//2^53 !!NOTE!! largest accurate double floating point whole value - public static B_64: number = 18446744073709551616;//2^64 !!NOTE!! Not accurate see B_53 + static B_16: number = 65536;//2^16 + static B_31: number = 2147483648;//2^31 + static B_32: number = 4294967296;//2^32 + static B_48: number = 281474976710656;//2^48 + static B_53: number = 9007199254740992;//2^53 !!NOTE!! largest accurate double floating point whole value + static B_64: number = 18446744073709551616;//2^64 !!NOTE!! Not accurate see B_53 - public static ONE_THIRD: number = 0.333333333333333333333333333333333; // 1.0/3.0; - public static TWO_THIRDS: number = 0.666666666666666666666666666666666; // 2.0/3.0; - public static ONE_SIXTH: number = 0.166666666666666666666666666666666; // 1.0/6.0; + static ONE_THIRD: number = 0.333333333333333333333333333333333; // 1.0/3.0; + static TWO_THIRDS: number = 0.666666666666666666666666666666666; // 2.0/3.0; + static ONE_SIXTH: number = 0.166666666666666666666666666666666; // 1.0/6.0; - public static COS_PI_3: number = 0.86602540378443864676372317075294;//COS( PI / 3 ) - public static SIN_2PI_3: number = 0.03654595;// SIN( 2*PI/3 ) + static COS_PI_3: number = 0.86602540378443864676372317075294;//COS( PI / 3 ) + static SIN_2PI_3: number = 0.03654595;// SIN( 2*PI/3 ) - public static CIRCLE_ALPHA: number = 0.5522847498307933984022516322796; //4*(Math.sqrt(2)-1)/3.0; + static CIRCLE_ALPHA: number = 0.5522847498307933984022516322796; //4*(Math.sqrt(2)-1)/3.0; - public static ON: bool = true; - public static OFF: bool = false; + static ON: bool = true; + static OFF: bool = false; - public static SHORT_EPSILON: number = 0.1;//round integer epsilon - public static PERC_EPSILON: number = 0.001;//percentage epsilon - public static EPSILON: number = 0.0001;//single float average epsilon - public static LONG_EPSILON: number = 0.00000001;//arbitrary 8 digit epsilon + static SHORT_EPSILON: number = 0.1;//round integer epsilon + static PERC_EPSILON: number = 0.001;//percentage epsilon + static EPSILON: number = 0.0001;//single float average epsilon + static LONG_EPSILON: number = 0.00000001;//arbitrary 8 digit epsilon public cosTable = []; public sinTable = []; @@ -712,7 +710,7 @@ module Phaser { * @method linear * @param {Any} v * @param {Any} k - * @static + * @public */ public linearInterpolation(v, k) { @@ -731,7 +729,7 @@ module Phaser { * @method Bezier * @param {Any} v * @param {Any} k - * @static + * @public */ public bezierInterpolation(v, k) { @@ -751,7 +749,7 @@ module Phaser { * @method CatmullRom * @param {Any} v * @param {Any} k - * @static + * @public */ public catmullRomInterpolation(v, k) { @@ -782,7 +780,7 @@ module Phaser { * @param {Any} p0 * @param {Any} p1 * @param {Any} t - * @static + * @public */ public linear(p0, p1, t) { @@ -794,7 +792,7 @@ module Phaser { * @method Bernstein * @param {Any} n * @param {Any} i - * @static + * @public */ public bernstein(n, i) { @@ -809,7 +807,7 @@ module Phaser { * @param {Any} p2 * @param {Any} p3 * @param {Any} t - * @static + * @public */ public catmullRom(p0, p1, p2, p3, t) { @@ -975,34 +973,6 @@ module Phaser { } - /** - * Finds the length of the given vector - * - * @param dx - * @param dy - * - * @return - */ - public vectorLength(dx:number, dy:number):number - { - return Math.sqrt(dx * dx + dy * dy); - } - - /** - * Finds the dot product value of two vectors - * - * @param ax Vector X - * @param ay Vector Y - * @param bx Vector X - * @param by Vector Y - * - * @return Dot product - */ - public dotProduct(ax:number, ay:number, bx:number, by:number):number - { - return ax * bx + ay * by; - } - /** * Shuffles the data in the given array into a new order * @param array The array to shuffle @@ -1029,7 +999,7 @@ module Phaser { * @param {Boolean} round - Round the distance to the nearest integer (default false) * @return {Number} The distance between this Point object and the destination Point object. **/ - public static distanceBetween(x1: number, y1: number, x2: number, y2: number): number { + public distanceBetween(x1: number, y1: number, x2: number, y2: number): number { var dx = x1 - x2; var dy = y1 - y2; @@ -1038,6 +1008,19 @@ module Phaser { } + /** + * Finds the length of the given vector + * + * @param dx + * @param dy + * + * @return + */ + public vectorLength(dx:number, dy:number):number + { + return Math.sqrt(dx * dx + dy * dy); + } + /** * Rotates the point around the x/y coordinates given to the desired angle and distance * @param point {Object} Any object with exposed x and y properties diff --git a/Phaser/math/LinkedList.ts b/Phaser/math/LinkedList.ts index 085fee2f..953eb4ce 100644 --- a/Phaser/math/LinkedList.ts +++ b/Phaser/math/LinkedList.ts @@ -1,4 +1,3 @@ -/// /// /** diff --git a/Phaser/physics/QuadTree.ts b/Phaser/math/QuadTree.ts similarity index 97% rename from Phaser/physics/QuadTree.ts rename to Phaser/math/QuadTree.ts index e6aa9831..c4d0b843 100644 --- a/Phaser/physics/QuadTree.ts +++ b/Phaser/math/QuadTree.ts @@ -1,6 +1,6 @@ /// -/// -/// +/// +/// /** * Phaser - QuadTree @@ -10,7 +10,7 @@ * or the A list against the B list. Handy for different things! */ -module Phaser.Physics { +module Phaser { export class QuadTree extends Rectangle { @@ -27,8 +27,8 @@ module Phaser.Physics { super(x, y, width, height); - this._headA = this._tailA = new LinkedList(); - this._headB = this._tailB = new LinkedList(); + 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) @@ -42,7 +42,7 @@ module Phaser.Physics { if (this._tailA.object != null) { this._ot = this._tailA; - this._tailA = new LinkedList(); + this._tailA = new Phaser.LinkedList(); this._ot.next = this._tailA; } @@ -60,7 +60,7 @@ module Phaser.Physics { if (this._tailB.object != null) { this._ot = this._tailB; - this._tailB = new LinkedList(); + this._tailB = new Phaser.LinkedList(); this._ot.next = this._tailB; } @@ -93,8 +93,8 @@ module Phaser.Physics { } // Reused temporary vars to help avoid gc spikes - private _iterator: LinkedList; - private _ot: LinkedList; + private _iterator: Phaser.LinkedList; + private _ot: Phaser.LinkedList; private _i; private _basic; private _members; @@ -126,25 +126,25 @@ module Phaser.Physics { * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ - private _headA: LinkedList; + private _headA: Phaser.LinkedList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ - private _tailA: LinkedList; + private _tailA: Phaser.LinkedList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ - private _headB: LinkedList; + private _headB: Phaser.LinkedList; /** * Refers to the internal A and B linked lists, * which are used to store objects in the leaves. */ - private _tailB: LinkedList; + private _tailB: Phaser.LinkedList; /** * Internal, governs and assists with the formation of the tree. @@ -244,7 +244,7 @@ module Phaser.Physics { /** * Internal, used during tree processing and overlap checks. */ - private static _iterator: LinkedList; + private static _iterator: Phaser.LinkedList; /** * Clean up memory. diff --git a/Phaser/physics/AABB.ts b/Phaser/physics/AABB.ts deleted file mode 100644 index e7a7dadd..00000000 --- a/Phaser/physics/AABB.ts +++ /dev/null @@ -1,208 +0,0 @@ -/// -/// -/// -/// -/// - -/** -* Phaser - Physics - AABB -*/ - -module Phaser.Physics { - - export class AABB implements IPhysicsShape { - - constructor(game: Game, sprite: Sprite, x: number, y: number, width: number, height: number) { - - this.game = game; - this.world = game.world.physics; - - if (sprite !== null) - { - this.sprite = sprite; - this.scale = Vec2Utils.clone(this.sprite.scale); - } - else - { - this.sprite = null; - this.physics = null; - this.scale = new Vec2(1, 1); - } - - this.bounds = new Rectangle(x + Math.round(width / 2), y + Math.round(height / 2), width, height); - this.position = new Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Vec2(0, 0); - - } - - public game: Game; - public world: PhysicsManager; - public sprite: Sprite; - public physics: Phaser.Components.Physics; - - public position: Vec2; - public oldPosition: Vec2; - public offset: Vec2; - public scale: Vec2; - public bounds: Rectangle; - - public preUpdate() { - - this.oldPosition.copyFrom(this.position); - - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - - if (this.sprite) - { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - - // Update scale / dimensions - if (Vec2Utils.equals(this.scale, this.sprite.scale) == false) - { - this.scale.copyFrom(this.sprite.scale); - this.bounds.width = this.sprite.width; - this.bounds.height = this.sprite.height; - } - } - - } - - public update() { - - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - - } - - public setSize(width: number, height: number) { - - this.bounds.width = width; - this.bounds.height = height; - - } - - public render(context:CanvasRenderingContext2D) { - - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.strokeRect(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight, this.bounds.width, this.bounds.height); - context.stroke(); - context.closePath(); - - // center point - context.fillStyle = 'rgb(0,255,0)'; - context.fillRect(this.position.x, this.position.y, 2, 2); - - if (this.physics.touching & Phaser.Types.LEFT) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if (this.physics.touching & Phaser.Types.RIGHT) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - - if (this.physics.touching & Phaser.Types.UP) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if (this.physics.touching & Phaser.Types.DOWN) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - - } - - public get hullWidth(): number { - - if (this.deltaX > 0) - { - return this.bounds.width + this.deltaX; - } - else - { - return this.bounds.width - this.deltaX; - } - - } - - public get hullHeight(): number { - - if (this.deltaY > 0) - { - return this.bounds.height + this.deltaY; - } - else - { - return this.bounds.height - this.deltaY; - } - - } - - public get hullX(): number { - - if (this.position.x < this.oldPosition.x) - { - return this.position.x; - } - else - { - return this.oldPosition.x; - } - - } - - public get hullY(): number { - - if (this.position.y < this.oldPosition.y) - { - return this.position.y; - } - else - { - return this.oldPosition.y; - } - - } - - public get deltaXAbs(): number { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - } - - public get deltaYAbs(): number { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - } - - public get deltaX(): number { - return this.position.x - this.oldPosition.x; - } - - public get deltaY(): number { - return this.position.y - this.oldPosition.y; - } - - } - -} \ No newline at end of file diff --git a/Phaser/physics/Body.ts b/Phaser/physics/Body.ts index 318aaccf..e57fcb55 100644 --- a/Phaser/physics/Body.ts +++ b/Phaser/physics/Body.ts @@ -1,9 +1,6 @@ /// /// /// -/// -/// -/// /** * Phaser - Physics - Body @@ -273,7 +270,7 @@ module Phaser.Physics { this.parent.texture.context.fillStyle = color; this.parent.texture.context.fillText('Sprite: (' + this.parent.frameBounds.width + ' x ' + this.parent.frameBounds.height + ')', x, y); //this.parent.texture.context.fillText('x: ' + this._parent.frameBounds.x.toFixed(1) + ' y: ' + this._parent.frameBounds.y.toFixed(1) + ' rotation: ' + this._parent.rotation.toFixed(1), x, y + 14); - this.parent.texture.context.fillText('x: ' + this.shape.bounds.x.toFixed(1) + ' y: ' + this.shape.bounds.y.toFixed(1) + ' rotation: ' + this._parent.rotation.toFixed(1), x, y + 14); + this.parent.texture.context.fillText('x: ' + this.bounds.x.toFixed(1) + ' y: ' + this.bounds.y.toFixed(1) + ' angle: ' + this.angle.toFixed(1), x, y + 14); this.parent.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); this.parent.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); diff --git a/Phaser/physics/Circle.ts b/Phaser/physics/Circle.ts deleted file mode 100644 index 2e910e9b..00000000 --- a/Phaser/physics/Circle.ts +++ /dev/null @@ -1,216 +0,0 @@ -/// -/// -/// -/// -/// - -/** -* Phaser - Physics - Circle -*/ - -module Phaser.Physics { - - export class Circle implements IPhysicsShape { - - constructor(game: Game, sprite: Sprite, x: number, y: number, diameter: number) { - - this.game = game; - this.world = game.world.physics; - - if (sprite !== null) - { - this.sprite = sprite; - this.scale = Vec2Utils.clone(this.sprite.scale); - } - else - { - this.sprite = null; - this.physics = null; - this.scale = new Vec2(1, 1); - } - - this.diameter = diameter; - this.radius = diameter / 2; - this.bounds = new Rectangle(x + Math.round(diameter / 2), y + Math.round(diameter / 2), diameter, diameter); - this.position = new Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Vec2(0, 0); - - } - - public game: Game; - public world: PhysicsManager; - public sprite: Sprite; - public physics: Phaser.Components.Physics; - - public position: Vec2; - public oldPosition: Vec2; - public offset: Vec2; - public scale: Vec2; - public bounds: Rectangle; - - public radius: number; - public diameter: number; - - public preUpdate() { - - this.oldPosition.copyFrom(this.position); - - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - - if (this.sprite) - { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - - // Update scale / dimensions - if (Vec2Utils.equals(this.scale, this.sprite.scale) == false) - { - this.scale.copyFrom(this.sprite.scale); - // needs to be radius based (+ square) - //this.bounds.width = this.sprite.width; - //this.bounds.height = this.sprite.height; - } - } - - } - - public update() { - - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - - } - - public setSize(width: number, height: number) { - - this.bounds.width = width; - this.bounds.height = height; - - } - - public render(context:CanvasRenderingContext2D) { - - // center point - context.fillStyle = 'rgba(255,0,0,0.5)'; - context.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2); - context.rect(this.position.x, this.position.y, 2, 2); - context.fill(); - - /* - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - */ - - } - - public get hullWidth(): number { - - if (this.deltaX > 0) - { - //return this.bounds.width + this.deltaX; - return this.diameter + this.deltaX; - } - else - { - //return this.bounds.width - this.deltaX; - return this.diameter - this.deltaX; - } - - } - - public get hullHeight(): number { - - if (this.deltaY > 0) - { - //return this.bounds.height + this.deltaY; - return this.diameter + this.deltaY; - } - else - { - //return this.bounds.height - this.deltaY; - return this.diameter - this.deltaY; - } - - } - - public get hullX(): number { - - if (this.position.x < this.oldPosition.x) - { - return this.position.x; - } - else - { - return this.oldPosition.x; - } - - } - - public get hullY(): number { - - if (this.position.y < this.oldPosition.y) - { - return this.position.y; - } - else - { - return this.oldPosition.y; - } - - } - - public get deltaXAbs(): number { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - } - - public get deltaYAbs(): number { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - } - - public get deltaX(): number { - return this.position.x - this.oldPosition.x; - } - - public get deltaY(): number { - return this.position.y - this.oldPosition.y; - } - - } - -} \ No newline at end of file diff --git a/Phaser/physics/Fixture.ts b/Phaser/physics/Fixture.ts deleted file mode 100644 index 3b0e20b4..00000000 --- a/Phaser/physics/Fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -/// -/// -/// -/// -/// -/// - -/** -* Phaser - Physics - Fixture -*/ - -module Phaser.Physics { - - export class Fixture { - - constructor(parent: Sprite, type: number) { - - this.parent = parent; - - // these are shape properties really - this.bounce = Vec2Utils.clone(this.game.world.physics.bounce); - this.friction = Vec2Utils.clone(this.game.world.physics.friction); - - } - - public game: Game; - public parent: Sprite; - - } - -} \ No newline at end of file diff --git a/Phaser/physics/IPhysicsBody.ts b/Phaser/physics/IPhysicsBody.ts deleted file mode 100644 index 6dbf961e..00000000 --- a/Phaser/physics/IPhysicsBody.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// -/// -/// - -/** -* Phaser - Physics - IPhysicsShape -*/ - -module Phaser.Physics { - - export interface IPhysicsBody { - - //game: Game; - //world: PhysicsManager; - //sprite: Sprite; - //physics: Phaser.Components.Physics; - - //position: Vec2; - //oldPosition: Vec2; - //offset: Vec2; - - //bounds: Rectangle; - - //setSize(width: number, height: number); - //preUpdate(); - //update(); - //render(context:CanvasRenderingContext2D); - - //hullX; - //hullY; - //hullWidth; - //hullHeight; - //deltaX; - //deltaY; - //deltaXAbs; - //deltaYAbs; - - } - -} diff --git a/Phaser/physics/IPhysicsShape.ts b/Phaser/physics/IPhysicsShape.ts deleted file mode 100644 index 15cb2a75..00000000 --- a/Phaser/physics/IPhysicsShape.ts +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// -/// - -/** -* Phaser - Physics - IPhysicsShape -*/ - -module Phaser.Physics { - - export interface IPhysicsShape { - - game: Game; - world: PhysicsManager; - sprite: Sprite; - physics: Phaser.Components.Physics; - - position: Vec2; - oldPosition: Vec2; - offset: Vec2; - - bounds: Rectangle; - //oH: number; - //oV: number; - - setSize(width: number, height: number); - preUpdate(); - update(); - render(context:CanvasRenderingContext2D); - - hullX; - hullY; - hullWidth; - hullHeight; - deltaX; - deltaY; - deltaXAbs; - deltaYAbs; - - } - -} diff --git a/Phaser/physics/PhysicsManager.ts b/Phaser/physics/PhysicsManager.ts index 7104d66e..3f6ccd15 100644 --- a/Phaser/physics/PhysicsManager.ts +++ b/Phaser/physics/PhysicsManager.ts @@ -2,7 +2,7 @@ /// /// /// -/// +/// /** * Phaser - PhysicsManager @@ -72,37 +72,25 @@ module Phaser.Physics { public bounce: Vec2; public angularDrag: number; + /** + * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects + * @type {number} + */ static OVERLAP_BIAS: number = 4; + /** + * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects + * @type {number} + */ + static TILE_OVERLAP: bool = false; + /** * @type {number} */ public worldDivisions: number = 6; - // Add some sanity checks here + remove method, etc /* - public add(shape: IPhysicsShape): IPhysicsShape { - - this._objects.push(shape); - return shape; - - } - - public remove(shape: IPhysicsShape) { - - this._length = this._objects.length; - - for (var i = 0; i < this._length; i++) - { - if (this._objects[i] === shape) - { - this._objects[i] = null; - } - } - - } - public update() { this._length = this._objects.length; @@ -222,74 +210,6 @@ module Phaser.Physics { } - private collideShapes(shapeA: IPhysicsShape, shapeB: IPhysicsShape) { - - if (shapeA.physics.immovable && shapeB.physics.immovable) - { - return; - } - - this._distance.setTo(0, 0); - this._tangent.setTo(0, 0); - - // Simple bounds check first - if (RectangleUtils.intersects(shapeA.bounds, shapeB.bounds)) - { - // Collide on the x-axis - if (shapeA.physics.velocity.x > 0 && shapeA.bounds.right > shapeB.bounds.x && shapeA.bounds.right <= shapeB.bounds.right) - { - // The right side of ShapeA hit the left side of ShapeB - this._distance.x = shapeB.bounds.x - shapeA.bounds.right; - - if (this._distance.x != 0) - { - this._tangent.x = -1; - } - } - else if (shapeA.physics.velocity.x < 0 && shapeA.bounds.x < shapeB.bounds.right && shapeA.bounds.x >= shapeB.bounds.x) - { - // The left side of ShapeA hit the right side of ShapeB - this._distance.x = shapeB.bounds.right - shapeA.bounds.x; - - if (this._distance.x != 0) - { - this._tangent.x = 1; - } - } - - // Collide on the y-axis - if (shapeA.physics.velocity.y < 0 && shapeA.bounds.y < shapeB.bounds.bottom && shapeA.bounds.y > shapeB.bounds.y) - { - console.log('top A -> bot B'); - // The top of ShapeA hit the bottom of ShapeB - this._distance.y = shapeB.bounds.bottom - shapeA.bounds.y; - console.log(shapeA.bounds, shapeB.bounds, this._distance.y); - - if (this._distance.y != 0) - { - this._tangent.y = 1; - } - } - else if (shapeA.physics.velocity.y > 0 && shapeA.bounds.bottom > shapeB.bounds.y && shapeA.bounds.bottom < shapeB.bounds.bottom) - { - // The bottom of ShapeA hit the top of ShapeB - this._distance.y = shapeB.bounds.y - shapeA.bounds.bottom; - - if (this._distance.y != 0) - { - this._tangent.y = -1; - } - } - - // Separate - if (this._distance.equals(0) == false) - { - //this.separate(shapeA, shapeB, this._distance, this._tangent); - } - } - - } - /** * The core Collision separation method. * @param body1 The first Physics.Body to separate @@ -305,18 +225,18 @@ module Phaser.Physics { } - private checkHullIntersection(shape1:IPhysicsShape, shape2:IPhysicsShape): bool { + private checkHullIntersection(body1: Body, body2:Body): bool { - //if ((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.bounds.width) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) - // maybe not bounds.width? - if ((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.hullWidth) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) - { - return true; - } - else - { - return false; - } + return ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)); + + //if ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)) + //{ + // return true; + //} + //else + //{ + // return false; + //} } @@ -547,8 +467,8 @@ module Phaser.Physics { - - private OLDseparate(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + /* + private TILEseparate(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { if (tangent.x == 1) { @@ -807,6 +727,7 @@ module Phaser.Physics { shapeA.position.y += distance.y; } + */ /** * Checks for overlaps between two objects using the world QuadTree. Can be Sprite vs. Sprite, Sprite vs. Group or Group vs. Group. @@ -846,6 +767,360 @@ module Phaser.Physics { } + + + + + + /** + * 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 + */ + public separateTile(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool, separateX: bool, separateY: bool): bool { + + //var separatedX: bool = this.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); + //var separatedY: bool = this.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); + + //return separatedX || separatedY; + + return false; + + } + + /** + * 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. + */ + /* + public separateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + var objDelta: number = object.x - object.last.x; + //var objDelta: number = object.collisionMask.deltaX; + + if (objDelta != 0) + { + // Check if the X hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //var objDeltaAbs: number = object.collisionMask.deltaXAbs; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.x + object.width - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (objDelta < 0) + { + overlap = object.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + //console.log(' + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + + /** + * 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. + */ + /* + public separateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 0; + var objDelta: number = object.y - object.last.y; + + if (objDelta != 0) + { + // Check if the Y hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.y + object.height - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (objDelta < 0) + { + overlap = object.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + + + /** + * 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. + */ + /* + public static NEWseparateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + + if (object.collisionMask.deltaX != 0) + { + // Check if the X hulls actually overlap + //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //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)) + { + var maxOverlap: number = object.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaX > 0) + { + //overlap = object.x + object.width - x; + overlap = object.collisionMask.right - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (object.collisionMask.deltaX < 0) + { + //overlap = object.x - width - x; + overlap = object.collisionMask.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + + /** + * 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. + */ + /* + public NEWseparateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 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: 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)) + { + //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + var maxOverlap: number = object.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaY > 0) + { + //overlap = object.y + object.height - y; + overlap = object.collisionMask.bottom - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (object.collisionMask.deltaY < 0) + { + //overlap = object.y - height - y; + overlap = object.collisionMask.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + } } \ No newline at end of file diff --git a/Phaser/utils/SpriteUtils.ts b/Phaser/utils/SpriteUtils.ts index c92f38f7..678bd113 100644 --- a/Phaser/utils/SpriteUtils.ts +++ b/Phaser/utils/SpriteUtils.ts @@ -8,69 +8,13 @@ * 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; - - + static _tempPoint: Point; static getAsPoints(sprite: Sprite): Phaser.Point[] { @@ -240,20 +184,18 @@ module Phaser { * * @return {boolean} Whether the object is on screen or not. */ - /* - static onScreen(camera: Camera = null): bool { + static onScreen(sprite: Sprite, camera: Camera = null): bool { if (camera == null) { - camera = this._game.camera; + camera = sprite.game.camera; } - this.getScreenXY(this._point, camera); + SpriteUtils.getScreenXY(sprite, SpriteUtils._tempPoint, camera); - return (this._point.x + this.width > 0) && (this._point.x < camera.width) && (this._point.y + this.height > 0) && (this._point.y < camera.height); + return (SpriteUtils._tempPoint.x + sprite.width > 0) && (SpriteUtils._tempPoint.x < camera.width) && (SpriteUtils._tempPoint.y + sprite.height > 0) && (SpriteUtils._tempPoint.y < camera.height); } - */ /** * Call this to figure out the on-screen position of the object. @@ -261,14 +203,13 @@ module Phaser { * @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. + * @return {Point} The Point 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 { + static getScreenXY(sprite: Sprite, point: Point = null, camera: Camera = null): Point { if (point == null) { - point = new MicroPoint(); + point = new Point(); } if (camera == null) @@ -276,15 +217,14 @@ module Phaser { 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 = sprite.x - camera.scroll.x * sprite.scrollFactor.x; + point.y = sprite.y - camera.scroll.y * sprite.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. @@ -305,7 +245,6 @@ 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. */ - /* static inCamera(camera: Rectangle, cameraOffsetX: number, cameraOffsetY: number): bool { // Object fixed in place regardless of the camera scrolling? Then it's always visible @@ -322,7 +261,6 @@ module Phaser { 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. @@ -331,21 +269,17 @@ module Phaser { * @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) { + static reset(sprite: Sprite, 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; + sprite.revive(); + sprite.body.touching = Types.NONE; + sprite.body.wasTouching = Types.NONE; + sprite.x = x; + sprite.y = y; + sprite.body.velocity.x = 0; + sprite.body.velocity.y = 0; } - */ /** * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 26839bf2..3868a21b 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -74,18 +74,10 @@ - aabb vs aabb 1.ts - - circle 1.ts - - - - test 1.ts - ballscroller.ts @@ -166,6 +158,8 @@ boot screen.ts - + + + \ No newline at end of file diff --git a/Tests/phaser.js b/Tests/phaser.js index bb887891..c3baaccc 100644 --- a/Tests/phaser.js +++ b/Tests/phaser.js @@ -1,5 +1,2175 @@ /// /** +* 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.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 Math.round(this.width / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "halfHeight", { + get: /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + function () { + return Math.round(this.height / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + get: /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @return {Number} + **/ + function () { + return this.y + this.height; + }, + set: /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @param {Number} value + **/ + function (value) { + if(value <= this.y) { + this.height = 0; + } else { + this.height = (this.y - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottomRight", { + set: /** + * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. + * @method bottomRight + * @param {Point} value + **/ + function (value) { + this.right = value.x; + this.bottom = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "left", { + get: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @method left + * @ return {number} + **/ + function () { + return this.x; + }, + set: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. + * However it does affect the width, whereas changing the x value does not affect the width property. + * @method left + * @param {Number} value + **/ + function (value) { + if(value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + get: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @return {Number} + **/ + function () { + return this.x + this.width; + }, + set: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @param {Number} value + **/ + function (value) { + if(value <= this.x) { + this.width = 0; + } else { + this.width = this.x + value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "volume", { + get: /** + * The volume of the Rectangle derived from width * height + * @method volume + * @return {Number} + **/ + function () { + return this.width * this.height; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "perimeter", { + get: /** + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @method perimeter + * @return {Number} + **/ + function () { + return (this.width * 2) + (this.height * 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + get: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @return {Number} + **/ + function () { + return this.y; + }, + set: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @param {Number} value + **/ + function (value) { + if(value >= this.bottom) { + this.height = 0; + this.y = value; + } else { + this.height = (this.bottom - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "topLeft", { + set: /** + * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. + * @method topLeft + * @param {Point} value + **/ + function (value) { + this.x = value.x; + this.y = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "empty", { + get: /** + * Determines whether or not this Rectangle object is empty. + * @method isEmpty + * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. + **/ + function () { + return (!this.width || !this.height); + }, + set: /** + * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. + * @method setEmpty + * @return {Rectangle} This rectangle object + **/ + function (value) { + return this.setTo(0, 0, 0, 0); + }, + enumerable: true, + configurable: true + }); + Rectangle.prototype.offset = /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Rectangle object by this amount. + * @param {Number} dy Moves the y value of the Rectangle object by this amount. + * @return {Rectangle} This Rectangle object. + **/ + function (dx, dy) { + this.x += dx; + this.y += dy; + return this; + }; + Rectangle.prototype.offsetPoint = /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Rectangle object. + * @return {Rectangle} This Rectangle object. + **/ + function (point) { + return this.offset(point.x, point.y); + }; + Rectangle.prototype.setTo = /** + * Sets the members of Rectangle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + function (x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }; + Rectangle.prototype.copyFrom = /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Rectangle} This Rectangle object. + **/ + function (source) { + return this.setTo(source.x, source.y, source.width, source.height); + }; + Rectangle.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + }; + return Rectangle; + })(); + Phaser.Rectangle = Rectangle; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - LinkedList +* +* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! +*/ +var Phaser; +(function (Phaser) { + var LinkedList = (function () { + /** + * Creates a new link, and sets object and next to null. + */ + function LinkedList() { + this.object = null; + this.next = null; + } + LinkedList.prototype.destroy = /** + * Clean up memory. + */ + function () { + this.object = null; + if(this.next != null) { + this.next.destroy(); + } + this.next = null; + }; + return LinkedList; + })(); + Phaser.LinkedList = LinkedList; +})(Phaser || (Phaser = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/// +/** +* Phaser - QuadTree +* +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! +*/ +var Phaser; +(function (Phaser) { + var QuadTree = (function (_super) { + __extends(QuadTree, _super); + /** + * Instantiate a new Quad Tree node. + * + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. + */ + function QuadTree(x, y, width, height, parent) { + if (typeof parent === "undefined") { parent = null; } + _super.call(this, x, y, width, height); + this._headA = this._tailA = new Phaser.LinkedList(); + this._headB = this._tailB = new Phaser.LinkedList(); + //Copy the parent's children (if there are any) + if(parent != null) { + if(parent._headA.object != null) { + this._iterator = parent._headA; + while(this._iterator != null) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + if(parent._headB.object != null) { + this._iterator = parent._headB; + while(this._iterator != null) { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + } else { + QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); + } + this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); + //Set up comparison/sort helpers + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + this._leftEdge = this.x; + this._rightEdge = this.x + this.width; + this._halfWidth = this.width / 2; + this._midpointX = this._leftEdge + this._halfWidth; + this._topEdge = this.y; + this._bottomEdge = this.y + this.height; + this._halfHeight = this.height / 2; + this._midpointY = this._topEdge + this._halfHeight; + } + QuadTree.A_LIST = 0; + QuadTree.B_LIST = 1; + QuadTree.prototype.destroy = /** + * Clean up memory. + */ + function () { + this._tailA.destroy(); + this._tailB.destroy(); + this._headA.destroy(); + this._headB.destroy(); + this._tailA = null; + this._tailB = null; + this._headA = null; + this._headB = null; + if(this._northWestTree != null) { + this._northWestTree.destroy(); + } + if(this._northEastTree != null) { + this._northEastTree.destroy(); + } + if(this._southEastTree != null) { + this._southEastTree.destroy(); + } + if(this._southWestTree != null) { + this._southWestTree.destroy(); + } + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + QuadTree._object = null; + QuadTree._processingCallback = null; + QuadTree._notifyCallback = null; + }; + QuadTree.prototype.load = /** + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof processCallback === "undefined") { processCallback = null; } + if (typeof context === "undefined") { context = null; } + this.add(objectOrGroup1, QuadTree.A_LIST); + if(objectOrGroup2 != null) { + this.add(objectOrGroup2, QuadTree.B_LIST); + QuadTree._useBothLists = true; + } else { + QuadTree._useBothLists = false; + } + QuadTree._notifyCallback = notifyCallback; + QuadTree._processingCallback = processCallback; + QuadTree._callbackContext = context; + }; + QuadTree.prototype.add = /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + function (objectOrGroup, list) { + QuadTree._list = list; + if(objectOrGroup.type == Phaser.Types.GROUP) { + this._i = 0; + this._members = objectOrGroup['members']; + this._l = objectOrGroup['length']; + while(this._i < this._l) { + this._basic = this._members[this._i++]; + if(this._basic != null && this._basic.exists) { + if(this._basic.type == Phaser.Types.GROUP) { + this.add(this._basic, list); + } else { + QuadTree._object = this._basic; + if(QuadTree._object.exists && QuadTree._object.body.allowCollisions) { + this.addObject(); + } + } + } + } + } else { + QuadTree._object = objectOrGroup; + if(QuadTree._object.exists && QuadTree._object.body.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.body.bounds.x) && (this._rightEdge <= QuadTree._object.body.bounds.right) && (this._topEdge >= QuadTree._object.body.bounds.y) && (this._bottomEdge <= QuadTree._object.body.bounds.bottom))) { + this.addToList(); + return; + } + //See if the selected object fits completely inside any of the quadrants + if((QuadTree._object.body.bounds.x > this._leftEdge) && (QuadTree._object.body.bounds.right < this._midpointX)) { + if((QuadTree._object.body.bounds.y > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.y > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.x > this._midpointX) && (QuadTree._object.body.bounds.right < this._rightEdge)) { + if((QuadTree._object.body.bounds.y > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.y > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.right > this._leftEdge) && (QuadTree._object.body.bounds.x < this._midpointX) && (QuadTree._object.body.bounds.bottom > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.right > this._midpointX) && (QuadTree._object.body.bounds.x < this._rightEdge) && (QuadTree._object.body.bounds.bottom > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.right > this._midpointX) && (QuadTree._object.body.bounds.x < this._rightEdge) && (QuadTree._object.body.bounds.bottom > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.right > this._leftEdge) && (QuadTree._object.body.bounds.x < this._midpointX) && (QuadTree._object.body.bounds.bottom > this._midpointY) && (QuadTree._object.body.bounds.y < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + } + }; + QuadTree.prototype.addToList = /** + * Internal function for recursively adding objects to leaf lists. + */ + function () { + if(QuadTree._list == QuadTree.A_LIST) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = QuadTree._object; + } else { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = QuadTree._object; + } + if(!this._canSubdivide) { + return; + } + if(this._northWestTree != null) { + this._northWestTree.addToList(); + } + if(this._northEastTree != null) { + this._northEastTree.addToList(); + } + if(this._southEastTree != null) { + this._southEastTree.addToList(); + } + if(this._southWestTree != null) { + this._southWestTree.addToList(); + } + }; + QuadTree.prototype.execute = /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + this._overlapProcessed = false; + if(this._headA.object != null) { + this._iterator = this._headA; + while(this._iterator != null) { + QuadTree._object = this._iterator.object; + if(QuadTree._useBothLists) { + QuadTree._iterator = this._headB; + } else { + QuadTree._iterator = this._iterator.next; + } + if(QuadTree._object.exists && (QuadTree._object.body.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { + this._overlapProcessed = true; + } + this._iterator = this._iterator.next; + } + } + //Advance through the tree by calling overlap on each child + if((this._northWestTree != null) && this._northWestTree.execute()) { + this._overlapProcessed = true; + } + if((this._northEastTree != null) && this._northEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southEastTree != null) && this._southEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southWestTree != null) && this._southWestTree.execute()) { + this._overlapProcessed = true; + } + return this._overlapProcessed; + }; + QuadTree.prototype.overlapNode = /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + //Walk the list and check for overlaps + this._overlapProcessed = false; + while(QuadTree._iterator != null) { + if(!QuadTree._object.exists || (QuadTree._object.body.allowCollisions <= 0)) { + break; + } + this._checkObject = QuadTree._iterator.object; + if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.body.allowCollisions <= 0)) { + QuadTree._iterator = QuadTree._iterator.next; + continue; + } + if(QuadTree._object.body.bounds.checkHullIntersection(this._checkObject.body.bounds)) { + //Execute callback functions if they exist + if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { + this._overlapProcessed = true; + } + if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { + if(QuadTree._callbackContext !== null) { + QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); + } else { + QuadTree._notifyCallback(QuadTree._object, this._checkObject); + } + } + } + QuadTree._iterator = QuadTree._iterator.next; + } + return this._overlapProcessed; + }; + return QuadTree; + })(Phaser.Rectangle); + Phaser.QuadTree = QuadTree; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - 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.multiplyByScalar = /** + * Multiply 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.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.equals = /** + * Check if both the x and y of this vector equal the given value. + * + * @return {Boolean} + */ + function (value) { + return (this.x == value && this.y == value); + }; + 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 - 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 * (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 = {})); +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; + Types.BODY_DISABLED = 0; + Types.BODY_DYNAMIC = 1; + Types.BODY_STATIC = 2; + Types.BODY_KINEMATIC = 3; + Types.LEFT = 0x0001; + Types.RIGHT = 0x0010; + Types.UP = 0x0100; + Types.DOWN = 0x1000; + Types.NONE = 0; + Types.CEILING = Types.UP; + Types.FLOOR = Types.DOWN; + Types.WALL = Types.LEFT | Types.RIGHT; + Types.ANY = Types.LEFT | Types.RIGHT | Types.UP | Types.DOWN; + return Types; + })(); + Phaser.Types = Types; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - Group +* +* This class is used for organising, updating and sorting game objects. +*/ +var Phaser; +(function (Phaser) { + 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. + * If this value is set it will call a canvas context save and restore before and after the render pass. + * Set to null to disable. + */ + this.globalCompositeOperation = null; + /** + * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. + * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. + * Set to 0 to disable. + */ + this.alpha = 0; + this.game = game; + this.type = Phaser.Types.GROUP; + this.exists = true; + this.visible = true; + this.members = []; + this.length = 0; + this._maxSize = maxSize; + this._marker = 0; + this._sortIndex = null; + this.cameraBlacklist = []; + } + Group.ASCENDING = -1; + Group.DESCENDING = 1; + 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) { + 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; + } + this._sortIndex = null; + }; + Group.prototype.update = /** + * 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 () { + 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(); + this._member.postUpdate(); + } + } + }; + Group.prototype.render = /** + * 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 (renderer, camera) { + if(camera.isHidden(this) == true) { + return; + } + if(this.globalCompositeOperation) { + this.game.stage.context.save(); + this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation; + } + if(this.alpha > 0) { + this._prevAlpha = this.game.stage.context.globalAlpha; + this.game.stage.context.globalAlpha = this.alpha; + } + 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.call(renderer, camera, this._member); + } + } + if(this.alpha > 0) { + this.game.stage.context.globalAlpha = this._prevAlpha; + } + if(this.globalCompositeOperation) { + this.game.stage.context.restore(); + } + }; + Object.defineProperty(Group.prototype, "maxSize", { + get: /** + * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. + */ + function () { + return this._maxSize; + }, + set: /** + * @private + */ + function (Size) { + this._maxSize = Size; + if(this._marker >= this._maxSize) { + this._marker = 0; + } + 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 + 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; + }, + enumerable: true, + configurable: true + }); + Group.prototype.add = /** + * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. + * Group will try to replace a null member of the array first. + * Failing that, Group will add it to the end of the member array, + * assuming there is room for it, and doubling the size of the array if necessary. + * + *

WARNING: If the group has a maxSize that has already been met, + * the object will NOT be added to the group!

+ * + * @param {Basic} Object The object you want to add to the group. + * @return {Basic} The same Basic object that was passed in. + */ + function (object) { + //Don't bother adding an object twice. + if(this.members.indexOf(Object) >= 0) { + return object; + } + //First, look for a null entry where we can add the object. + 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; + } + 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; + } else if(this.members.length * 2 <= this._maxSize) { + this.members.length *= 2; + } else { + this.members.length = this._maxSize; + } + } else { + this.members.length *= 2; + } + //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[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. + * + *

If you specified a maximum size for this group (like in Emitter), + * then recycle will employ what we're calling "rotating" recycling. + * Recycle() will first check to see if the group is at capacity yet. + * If group is not yet at capacity, recycle() returns a new object. + * If the group IS at capacity, then recycle() just returns the next object in line.

+ * + *

If you did NOT specify a maximum size for this group, + * then recycle() will employ what we're calling "grow-style" recycling. + * Recycle() will return either the first object with exists == false, + * or, finding none, add a new object to the array, + * doubling the size of the array if necessary.

+ * + *

WARNING: If this function needs to create a new object, + * and no object class was provided, it will return null + * instead of a valid object!

+ * + * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! + * + * @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; } + if(this._maxSize > 0) { + if(this.length < this._maxSize) { + if(objectClass == null) { + return null; + } + return this.add(new objectClass(this.game)); + } else { + this._member = this.members[this._marker++]; + if(this._marker >= this._maxSize) { + this._marker = 0; + } + return this._member; + } + } else { + this._member = this.getFirstAvailable(objectClass); + if(this._member != null) { + return this._member; + } + if(objectClass == null) { + return null; + } + return this.add(new objectClass(this.game)); + } + }; + Group.prototype.remove = /** + * Removes an object from the group. + * + * @param {Basic} object The Basic you want to remove. + * @param {boolean} splice Whether the object should be cut from the array entirely or not. + * + * @return {Basic} The removed object. + */ + function (object, splice) { + if (typeof splice === "undefined") { splice = false; } + this._i = this.members.indexOf(object); + if(this._i < 0 || (this._i >= this.members.length)) { + return null; + } + if(splice) { + this.members.splice(this._i, 1); + this.length--; + } else { + this.members[this._i] = null; + } + return object; + }; + Group.prototype.replace = /** + * Replaces an existing Basic with a new one. + * + * @param {Basic} oldObject The object you want to replace. + * @param {Basic} newObject The new object you want to use instead. + * + * @return {Basic} The new object. + */ + function (oldObject, newObject) { + this._i = this.members.indexOf(oldObject); + if(this._i < 0 || (this._i >= this.members.length)) { + return null; + } + this.members[this._i] = newObject; + return newObject; + }; + Group.prototype.sort = /** + * Call this function to sort the group according to a particular value and order. + * For example, to sort game objects for Zelda-style overlaps you might call + * myGroup.sort("y",Group.ASCENDING) at the bottom of your + * State.update() override. To sort all existing objects after + * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). + * + * @param {string} index The string name of the member variable you want to sort on. Default value is "y". + * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. + */ + function (index, order) { + if (typeof index === "undefined") { index = "y"; } + if (typeof order === "undefined") { order = Group.ASCENDING; } + this._sortIndex = index; + this._sortOrder = order; + this.members.sort(this.sortHandler); + }; + Group.prototype.setAll = /** + * Go through and set the specified variable to the specified value on all members of the group. + * + * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". + * @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; } + 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 { + this._member[variableName] = value; + } + } + } + }; + Group.prototype.callAll = /** + * Go through and call the specified function on all members of the group. + * Currently only works on functions that have no required parameters. + * + * @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; } + 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 { + this._member[functionName](); + } + } + } + }; + Group.prototype.forEach = /** + * @param {function} callback + * @param {boolean} recursive + */ + function (callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + 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, this._member); + } + } + } + }; + Group.prototype.forEachAlive = /** + * @param {any} context + * @param {function} callback + * @param {boolean} recursive + */ + function (context, callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + 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, this._member); + } + } + } + }; + Group.prototype.getFirstAvailable = /** + * Call this function to retrieve the first object with exists == false in the group. + * This is handy for recycling in general, e.g. respawning enemies. + * + * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. + * + * @return {any} A Basic currently flagged as not existing. + */ + 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; + }; + Group.prototype.getFirstNull = /** + * Call this function to retrieve the first index set to 'null'. + * Returns -1 if no index stores a null object. + * + * @return {number} An int indicating the first null slot in the group. + */ + function () { + this._i = 0; + while(this._i < this.length) { + if(this.members[this._i] == null) { + return this._i; + } else { + this._i++; + } + } + return -1; + }; + Group.prototype.getFirstExtant = /** + * Call this function to retrieve the first object with exists == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as existing. + */ + function () { + 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; + }; + Group.prototype.getFirstAlive = /** + * Call this function to retrieve the first object with dead == false in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as not dead. + */ + function () { + 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; + }; + Group.prototype.getFirstDead = /** + * Call this function to retrieve the first object with dead == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as dead. + */ + function () { + 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; + }; + Group.prototype.countLiving = /** + * Call this function to find out how many members of the group are not dead. + * + * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. + */ + function () { + 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(this._member.exists && this._member.alive) { + this._count++; + } + } + } + return this._count; + }; + Group.prototype.countDead = /** + * Call this function to find out how many members of the group are dead. + * + * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. + */ + function () { + 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(!this._member.alive) { + this._count++; + } + } + } + return this._count; + }; + Group.prototype.getRandom = /** + * Returns a member at random from the group. + * + * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {number} Length Optional restriction on the number of values you want to randomly select from. + * + * @return {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; + } + return this.game.math.getRandom(this.members, startIndex, length); + }; + Group.prototype.clear = /** + * Remove all instances of Basic subclass (Basic, Block, etc) from the list. + * WARNING: does not destroy() or kill() any of these objects! + */ + function () { + this.length = this.members.length = 0; + }; + Group.prototype.kill = /** + * Calls kill on the group's members and then on the group itself. + */ + function () { + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && this._member.exists) { + this._member.kill(); + } + } + }; + Group.prototype.sortHandler = /** + * Helper function for the sort process. + * + * @param {Basic} Obj1 The first object being sorted. + * @param {Basic} Obj2 The second object being sorted. + * + * @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]) { + return this._sortOrder; + } else if(obj1[this._sortIndex] > obj2[this._sortIndex]) { + return -this._sortOrder; + } + return 0; + }; + return Group; + })(); + Phaser.Group = Group; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - SignalBinding +* +* An object that represents a binding between a Signal and a listener function. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ +*/ +var Phaser; +(function (Phaser) { + var SignalBinding = (function () { + /** + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {boolean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). + */ + function SignalBinding(signal, listener, isOnce, listenerContext, priority) { + if (typeof priority === "undefined") { priority = 0; } + /** + * If binding is active and should be executed. + * @type boolean + */ + this.active = true; + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + this.params = null; + this._listener = listener; + this._isOnce = isOnce; + this.context = listenerContext; + this._signal = signal; + this.priority = priority || 0; + } + SignalBinding.prototype.execute = /** + * Call listener passing arbitrary parameters. + *

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

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

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

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

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

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

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

+ */ + function () { + this.removeAll(); + delete this._bindings; + delete this._prevParams; + }; + Signal.prototype.toString = /** + * @return {string} String representation of the object. + */ + function () { + return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; + }; + return Signal; + })(); + Phaser.Signal = Signal; +})(Phaser || (Phaser = {})); +/// +/** * Phaser - Loader * * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. @@ -678,7 +2848,7 @@ var Phaser; * The global random number generator seed (for deterministic behavior in recordings and saves). */ this.globalSeed = Math.random(); - this._game = game; + this.game = game; } GameMath.PI = 3.141592653589793; GameMath.PI_2 = 1.5707963267948965; @@ -1296,7 +3466,7 @@ var Phaser; * @method linear * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var m = v.length - 1; @@ -1314,7 +3484,7 @@ var Phaser; * @method Bezier * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var b = 0; @@ -1328,7 +3498,7 @@ var Phaser; * @method CatmullRom * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var m = v.length - 1; @@ -1354,7 +3524,7 @@ var Phaser; * @param {Any} p0 * @param {Any} p1 * @param {Any} t - * @static + * @public */ function (p0, p1, t) { return (p1 - p0) * t + p0; @@ -1363,7 +3533,7 @@ var Phaser; * @method Bernstein * @param {Any} n * @param {Any} i - * @static + * @public */ function (n, i) { return this.factorial(n) / this.factorial(i) / this.factorial(n - i); @@ -1375,7 +3545,7 @@ var Phaser; * @param {Any} p2 * @param {Any} p3 * @param {Any} t - * @static + * @public */ function (p0, p1, p2, p3, t) { var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; @@ -1504,30 +3674,6 @@ var Phaser; return s; } }; - GameMath.prototype.vectorLength = /** - * Finds the length of the given vector - * - * @param dx - * @param dy - * - * @return - */ - function (dx, dy) { - return Math.sqrt(dx * dx + dy * dy); - }; - GameMath.prototype.dotProduct = /** - * Finds the dot product value of two vectors - * - * @param ax Vector X - * @param ay Vector Y - * @param bx Vector X - * @param by Vector Y - * - * @return Dot product - */ - function (ax, ay, bx, by) { - return ax * bx + ay * by; - }; GameMath.prototype.shuffleArray = /** * Shuffles the data in the given array into a new order * @param array The array to shuffle @@ -1542,18 +3688,29 @@ var Phaser; } return array; }; - GameMath.distanceBetween = /** + GameMath.prototype.distanceBetween = /** * Returns the distance from this Point object to the given Point object. * @method distanceFrom * @param {Point} target - The destination Point object. * @param {Boolean} round - Round the distance to the nearest integer (default false) * @return {Number} The distance between this Point object and the destination Point object. **/ - function distanceBetween(x1, y1, x2, y2) { + function (x1, y1, x2, y2) { var dx = x1 - x2; var dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); }; + GameMath.prototype.vectorLength = /** + * Finds the length of the given vector + * + * @param dx + * @param dy + * + * @return + */ + function (dx, 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 * @param point {Object} Any object with exposed x and y properties @@ -1811,356 +3968,6 @@ var Phaser; })(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.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 Math.round(this.width / 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "halfHeight", { - get: /** - * Half of the height of the rectangle - * @property halfHeight - * @type Number - **/ - function () { - return Math.round(this.height / 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottom", { - get: /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @return {Number} - **/ - function () { - return this.y + this.height; - }, - set: /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @param {Number} value - **/ - function (value) { - if(value <= this.y) { - this.height = 0; - } else { - this.height = (this.y - value); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottomRight", { - set: /** - * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. - * @method bottomRight - * @param {Point} value - **/ - function (value) { - this.right = value.x; - this.bottom = value.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "left", { - get: /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @ return {number} - **/ - function () { - return this.x; - }, - set: /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width, whereas changing the x value does not affect the width property. - * @method left - * @param {Number} value - **/ - function (value) { - if(value >= this.right) { - this.width = 0; - } else { - this.width = this.right - value; - } - this.x = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "right", { - get: /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {Number} - **/ - function () { - return this.x + this.width; - }, - set: /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {Number} value - **/ - function (value) { - if(value <= this.x) { - this.width = 0; - } else { - this.width = this.x + value; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "volume", { - get: /** - * The volume of the Rectangle derived from width * height - * @method volume - * @return {Number} - **/ - function () { - return this.width * this.height; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "perimeter", { - get: /** - * The perimeter size of the Rectangle. This is the sum of all 4 sides. - * @method perimeter - * @return {Number} - **/ - function () { - return (this.width * 2) + (this.height * 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "top", { - get: /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @return {Number} - **/ - function () { - return this.y; - }, - set: /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @param {Number} value - **/ - function (value) { - if(value >= this.bottom) { - this.height = 0; - this.y = value; - } else { - this.height = (this.bottom - value); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "topLeft", { - set: /** - * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. - * @method topLeft - * @param {Point} value - **/ - function (value) { - this.x = value.x; - this.y = value.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "empty", { - get: /** - * Determines whether or not this Rectangle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. - **/ - function () { - return (!this.width || !this.height); - }, - set: /** - * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. - * @method setEmpty - * @return {Rectangle} This rectangle object - **/ - function (value) { - return this.setTo(0, 0, 0, 0); - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.offset = /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Rectangle object by this amount. - * @param {Number} dy Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - function (dx, dy) { - this.x += dx; - this.y += dy; - return this; - }; - Rectangle.prototype.offsetPoint = /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - function (point) { - return this.offset(point.x, point.y); - }; - Rectangle.prototype.setTo = /** - * Sets the members of Rectangle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - function (x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - return this; - }; - Rectangle.prototype.copyFrom = /** - * Copies the x, y, width and height properties from any given object to this Rectangle. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Rectangle} This Rectangle object. - **/ - function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }; - Rectangle.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - function () { - return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; - }; - return Rectangle; - })(); - Phaser.Rectangle = Rectangle; -})(Phaser || (Phaser = {})); -/// -/** * Phaser - AnimationLoader * * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. @@ -3232,291 +5039,6 @@ var Phaser; 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; - /** - * 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 = {})); -/// /// /// /// @@ -3525,22 +5047,11 @@ var 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.getAsPoints = function getAsPoints(sprite) { var out = []; // top left @@ -3553,7 +5064,7 @@ var Phaser; out.push(new Phaser.Point(sprite.x, sprite.y + sprite.height)); return out; }; - SpriteUtils.setBounds = /** + SpriteUtils.onScreen = /** * 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! @@ -3698,51 +5209,38 @@ var Phaser; * * @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); - - } - */ - /** + function onScreen(sprite, camera) { + if (typeof camera === "undefined") { camera = null; } + if(camera == null) { + camera = sprite.game.camera; + } + SpriteUtils.getScreenXY(sprite, SpriteUtils._tempPoint, camera); + return (SpriteUtils._tempPoint.x + sprite.width > 0) && (SpriteUtils._tempPoint.x < camera.width) && (SpriteUtils._tempPoint.y + sprite.height > 0) && (SpriteUtils._tempPoint.y < camera.height); + }; + SpriteUtils.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. + * @return {Point} The Point 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; - - } - */ - /** + function getScreenXY(sprite, point, camera) { + if (typeof point === "undefined") { point = null; } + if (typeof camera === "undefined") { camera = null; } + if(point == null) { + point = new Phaser.Point(); + } + if(camera == null) { + camera = this._game.camera; + } + point.x = sprite.x - camera.scroll.x * sprite.scrollFactor.x; + point.y = sprite.y - camera.scroll.y * sprite.scrollFactor.y; + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + return point; + }; + SpriteUtils.inCamera = /** * 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 @@ -3760,47 +5258,34 @@ var 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. */ - /* - 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); - - } - */ - /** + function inCamera(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); + }; + SpriteUtils.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. */ - /* - 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; - - } - */ - /** + function reset(sprite, x, y) { + sprite.revive(); + sprite.body.touching = Phaser.Types.NONE; + sprite.body.wasTouching = Phaser.Types.NONE; + sprite.x = x; + sprite.y = y; + sprite.body.velocity.x = 0; + sprite.body.velocity.y = 0; + }; + SpriteUtils.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. @@ -3989,10 +5474,499 @@ var Phaser; })(Phaser || (Phaser = {})); /// /// +/** +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. +* +*/ +var Phaser; +(function (Phaser) { + var Vec2Utils = (function () { + function Vec2Utils() { } + Vec2Utils.add = /** + * Adds two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors. + */ + function add(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x + b.x, a.y + b.y); + }; + Vec2Utils.subtract = /** + * Subtracts two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the difference of the two vectors. + */ + function subtract(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x - b.x, a.y - b.y); + }; + Vec2Utils.multiply = /** + * Multiplies two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. + */ + function multiply(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * b.x, a.y * b.y); + }; + Vec2Utils.divide = /** + * Divides two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the sum of the two vectors divided. + */ + function divide(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x / b.x, a.y / b.y); + }; + Vec2Utils.scale = /** + * Scales a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {number} s Scaling value. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function scale(a, s, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x * s, a.y * s); + }; + Vec2Utils.perp = /** + * Rotate a 2D vector by 90 degrees. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is the scaled vector. + */ + function perp(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.y, -a.x); + }; + Vec2Utils.equals = /** + * Checks if two 2D vectors are equal. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Boolean} + */ + function equals(a, b) { + return a.x == b.x && a.y == b.y; + }; + Vec2Utils.epsilonEquals = /** + * + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} epsilon + * @return {Boolean} + */ + function epsilonEquals(a, b, epsilon) { + return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; + }; + Vec2Utils.distance = /** + * Get the distance between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distance(a, b) { + return Math.sqrt(Vec2Utils.distanceSq(a, b)); + }; + Vec2Utils.distanceSq = /** + * Get the distance squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function distanceSq(a, b) { + return ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)); + }; + Vec2Utils.project = /** + * Project two 2D vectors onto another vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function project(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b) / b.lengthSq(); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.projectUnit = /** + * Project this vector onto a vector of unit length. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function projectUnit(a, b, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var amt = a.dot(b); + if(amt != 0) { + out.setTo(amt * b.x, amt * b.y); + } + return out; + }; + Vec2Utils.normalRightHand = /** + * Right-hand normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalRightHand(a, out) { + if (typeof out === "undefined") { out = this; } + return out.setTo(a.y * -1, a.x); + }; + Vec2Utils.normalize = /** + * Normalize (make unit length) a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function normalize(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var m = a.length(); + if(m != 0) { + out.setTo(a.x / m, a.y / m); + } + return out; + }; + Vec2Utils.dot = /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function dot(a, b) { + return ((a.x * b.x) + (a.y * b.y)); + }; + Vec2Utils.cross = /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function cross(a, b) { + return ((a.x * b.y) - (a.y * b.x)); + }; + Vec2Utils.angle = /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angle(a, b) { + return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y); + }; + Vec2Utils.angleSq = /** + * The angle squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + function angleSq(a, b) { + return a.subtract(b).angle(b.subtract(a)); + }; + Vec2Utils.rotate = /** + * Rotate a 2D vector around the origin to the given angle (theta). + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Number} theta The angle of rotation in radians. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + function rotate(a, b, theta, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + var x = a.x - b.x; + var y = a.y - b.y; + return out.setTo(x * Math.cos(theta) - y * Math.sin(theta) + b.x, x * Math.sin(theta) + y * Math.cos(theta) + b.y); + }; + Vec2Utils.clone = /** + * Clone a 2D vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2 that is a copy of the source Vec2. + */ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Vec2(); } + return out.setTo(a.x, a.y); + }; + return Vec2Utils; + })(); + Phaser.Vec2Utils = Vec2Utils; + /** + * Reflect this vector on an arbitrary axis. + * + * @param {Vec2} axis The vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflect(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.project(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + */ + /** + * Reflect this vector on an arbitrary axis (represented by a unit vector) + * + * @param {Vec2} axis The unit vector representing the axis. + * @return {Vec2} This for chaining. + */ + /* + static reflectN(axis): Vec2 { + + var x = this.x; + var y = this.y; + this.projectN(axis).scale(2); + this.x -= x; + this.y -= y; + + return this; + + } + + static getMagnitude(): number { + return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); + } + */ + })(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /// + /// + /** + * Phaser - Physics - Body + */ + (function (Physics) { + var Body = (function () { + function Body(parent, type) { + this.angularVelocity = 0; + this.angularAcceleration = 0; + this.angularDrag = 0; + this.maxAngular = 10000; + this.mass = 1; + this.parent = parent; + this.game = parent.game; + this.type = type; + // Fixture properties + // Will extend into its own class at a later date - can move the fixture defs there and add shape support, but this will do for 1.0 release + this.bounds = new Phaser.Rectangle(parent.x + Math.round(parent.width / 2), parent.y + Math.round(parent.height / 2), parent.width, parent.height); + this.bounce = Phaser.Vec2Utils.clone(this.game.world.physics.bounce); + // Body properties + this.gravity = Phaser.Vec2Utils.clone(this.game.world.physics.gravity); + this.velocity = new Phaser.Vec2(); + this.acceleration = new Phaser.Vec2(); + this.drag = Phaser.Vec2Utils.clone(this.game.world.physics.drag); + this.maxVelocity = new Phaser.Vec2(10000, 10000); + this.angle = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + this.angularDrag = 0; + this.touching = Phaser.Types.NONE; + this.wasTouching = Phaser.Types.NONE; + this.allowCollisions = Phaser.Types.ANY; + this.position = new Phaser.Vec2(parent.x + this.bounds.halfWidth, parent.y + this.bounds.halfHeight); + this.oldPosition = new Phaser.Vec2(parent.x + this.bounds.halfWidth, parent.y + this.bounds.halfHeight); + this.offset = new Phaser.Vec2(); + } + Body.prototype.preUpdate = function () { + this.oldPosition.copyFrom(this.position); + this.bounds.x = this.position.x - this.bounds.halfWidth; + this.bounds.y = this.position.y - this.bounds.halfHeight; + if(this.parent.scale.equals(1) == false) { + } + }; + Body.prototype.postUpdate = // Shall we do this? Or just update the values directly in the separate functions? But then the bounds will be out of sync - as long as + // the bounds are updated and used in calculations then we can do one final sprite movement here I guess? + function () { + // if this is all it does maybe move elsewhere? Sprite postUpdate? + if(this.type !== Phaser.Types.BODY_DISABLED) { + this.game.world.physics.updateMotion(this); + this.parent.x = (this.position.x - this.bounds.halfWidth) - this.offset.x; + this.parent.y = (this.position.y - this.bounds.halfHeight) - this.offset.y; + this.wasTouching = this.touching; + this.touching = Phaser.Types.NONE; + } + }; + Object.defineProperty(Body.prototype, "hullWidth", { + get: function () { + if(this.deltaX > 0) { + return this.bounds.width + this.deltaX; + } else { + return this.bounds.width - this.deltaX; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "hullHeight", { + get: function () { + if(this.deltaY > 0) { + return this.bounds.height + this.deltaY; + } else { + return this.bounds.height - this.deltaY; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "hullX", { + get: function () { + if(this.position.x < this.oldPosition.x) { + return this.position.x; + } else { + return this.oldPosition.x; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "hullY", { + get: function () { + if(this.position.y < this.oldPosition.y) { + return this.position.y; + } else { + return this.oldPosition.y; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "deltaXAbs", { + get: function () { + return (this.deltaX > 0 ? this.deltaX : -this.deltaX); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "deltaYAbs", { + get: function () { + return (this.deltaY > 0 ? this.deltaY : -this.deltaY); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "deltaX", { + get: function () { + return this.position.x - this.oldPosition.x; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Body.prototype, "deltaY", { + get: function () { + return this.position.y - this.oldPosition.y; + }, + enumerable: true, + configurable: true + }); + Body.prototype.render = // MOVE THESE TO A UTIL + function (context) { + context.beginPath(); + context.strokeStyle = 'rgb(0,255,0)'; + context.strokeRect(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight, this.bounds.width, this.bounds.height); + context.stroke(); + context.closePath(); + // center point + context.fillStyle = 'rgb(0,255,0)'; + context.fillRect(this.position.x, this.position.y, 2, 2); + if(this.touching & Phaser.Types.LEFT) { + context.beginPath(); + context.strokeStyle = 'rgb(255,0,0)'; + context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); + context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); + context.stroke(); + context.closePath(); + } + if(this.touching & Phaser.Types.RIGHT) { + context.beginPath(); + context.strokeStyle = 'rgb(255,0,0)'; + context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); + context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); + context.stroke(); + context.closePath(); + } + if(this.touching & Phaser.Types.UP) { + context.beginPath(); + context.strokeStyle = 'rgb(255,0,0)'; + context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); + context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); + context.stroke(); + context.closePath(); + } + if(this.touching & Phaser.Types.DOWN) { + context.beginPath(); + context.strokeStyle = 'rgb(255,0,0)'; + context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); + context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); + context.stroke(); + context.closePath(); + } + }; + Body.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.parent.texture.context.fillStyle = color; + this.parent.texture.context.fillText('Sprite: (' + this.parent.frameBounds.width + ' x ' + this.parent.frameBounds.height + ')', x, y); + //this.parent.texture.context.fillText('x: ' + this._parent.frameBounds.x.toFixed(1) + ' y: ' + this._parent.frameBounds.y.toFixed(1) + ' rotation: ' + this._parent.rotation.toFixed(1), x, y + 14); + this.parent.texture.context.fillText('x: ' + this.bounds.x.toFixed(1) + ' y: ' + this.bounds.y.toFixed(1) + ' angle: ' + this.angle.toFixed(1), x, y + 14); + this.parent.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); + this.parent.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); + }; + return Body; + })(); + Physics.Body = Body; + })(Phaser.Physics || (Phaser.Physics = {})); + var Physics = Phaser.Physics; +})(Phaser || (Phaser = {})); +/// +/// /// /// /// -/// +/// /** * Phaser - Sprite * @@ -4007,20 +5981,13 @@ var Phaser; * @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. + * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) */ - function Sprite(game, x, y, key, width, height) { + function Sprite(game, x, y, key, bodyType) { 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; } - /** - * Rotation angle of this object. - * @type {number} - */ - this._rotation = 0; + if (typeof bodyType === "undefined") { bodyType = Phaser.Types.BODY_DISABLED; } /** * A boolean representing if the Sprite has been modified in any way via a scale, rotate, flip or skew. */ @@ -4038,12 +6005,12 @@ var Phaser; */ this.z = 0; /** - * This value is added to the rotation of the Sprite. + * This value is added to the angle 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. + * angleOffset to 90 and it would correspond correctly with Phasers right-handed coordinate system. * @type {number} */ - this.rotationOffset = 0; + this.angleOffset = 0; this.game = game; this.type = Phaser.Types.SPRITE; this.render = game.renderer.renderSprite; @@ -4051,7 +6018,8 @@ var Phaser; this.active = true; this.visible = true; this.alive = true; - this.frameBounds = new Phaser.Rectangle(x, y, width, height); + // We give it a default size of 16x16 but when the texture loads (if given) it will reset this + this.frameBounds = new Phaser.Rectangle(x, y, 16, 16); this.scrollFactor = new Phaser.Vec2(1, 1); this.x = x; this.y = y; @@ -4059,26 +6027,27 @@ var Phaser; ; this.animations = new Phaser.Components.AnimationManager(this); this.texture = new Phaser.Components.Texture(this, key); + this.cameraBlacklist = []; // Transform related (if we add any more then move to a component) this.origin = new Phaser.Vec2(0, 0); this.scale = new Phaser.Vec2(1, 1); this.skew = new Phaser.Vec2(0, 0); - this.physics = new Phaser.Components.Physics(this); - this.physics.shape.physics = this.physics; + // If a texture has been given the body will be set to that size, otherwise 16x16 + this.body = new Phaser.Physics.Body(this, bodyType); } - Object.defineProperty(Sprite.prototype, "rotation", { + Object.defineProperty(Sprite.prototype, "angle", { get: /** - * The rotation of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. + * The angle of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. */ function () { - return this._rotation; + return this.body.angle; }, set: /** - * Set the rotation of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. + * Set the angle of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. * The value is automatically wrapped to be between 0 and 360. */ function (value) { - this._rotation = this.game.math.wrap(value, 360, 0); + this.body.angle = this.game.math.wrap(value, 360, 0); }, enumerable: true, configurable: true @@ -4141,7 +6110,7 @@ var Phaser; function () { this.frameBounds.x = this.x; this.frameBounds.y = this.y; - if(this.modified == false && (!this.scale.equals(1) || !this.skew.equals(0) || this.rotation != 0 || this.rotationOffset != 0 || this.texture.flippedX || this.texture.flippedY)) { + if(this.modified == false && (!this.scale.equals(1) || !this.skew.equals(0) || this.angle != 0 || this.angleOffset != 0 || this.texture.flippedX || this.texture.flippedY)) { this.modified = true; } }; @@ -4155,7 +6124,7 @@ var Phaser; */ function () { this.animations.update(); - this.physics.update(); + this.body.postUpdate(); /* if (this.worldBounds != null) { @@ -4188,17 +6157,13 @@ var Phaser; } } - this.collisionMask.update(); - if (this.inputEnabled) { this.updateInput(); } - this.wasTouching = this.touching; - this.touching = Collision.NONE; */ - if(this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.rotation == 0 && this.rotationOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) { + if(this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.angle == 0 && this.angleOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) { this.modified = false; } }; @@ -4207,6 +6172,25 @@ var Phaser; */ function () { }; + Sprite.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; + }; + Sprite.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; + }; return Sprite; })(); Phaser.Sprite = Sprite; @@ -5562,1051 +7546,1522 @@ var Phaser; Phaser.Tween = Tween; })(Phaser || (Phaser = {})); /// -/// +/// /** -* Phaser - Vec2Utils -* -* A collection of methods useful for manipulating and performing operations on 2D vectors. +* 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 Vec2Utils = (function () { - function Vec2Utils() { } - Vec2Utils.add = /** - * Adds two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors. - */ - function add(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x + b.x, a.y + b.y); - }; - Vec2Utils.subtract = /** - * Subtracts two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the difference of the two vectors. - */ - function subtract(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x - b.x, a.y - b.y); - }; - Vec2Utils.multiply = /** - * Multiplies two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors multiplied. - */ - function multiply(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x * b.x, a.y * b.y); - }; - Vec2Utils.divide = /** - * Divides two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the sum of the two vectors divided. - */ - function divide(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x / b.x, a.y / b.y); - }; - Vec2Utils.scale = /** - * Scales a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {number} s Scaling value. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the scaled vector. - */ - function scale(a, s, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x * s, a.y * s); - }; - Vec2Utils.perp = /** - * Rotate a 2D vector by 90 degrees. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is the scaled vector. - */ - function perp(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.y, -a.x); - }; - Vec2Utils.equals = /** - * Checks if two 2D vectors are equal. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Boolean} - */ - function equals(a, b) { - return a.x == b.x && a.y == b.y; - }; - Vec2Utils.epsilonEquals = /** - * - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} epsilon - * @return {Boolean} - */ - function epsilonEquals(a, b, epsilon) { - return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon; - }; - Vec2Utils.distance = /** - * Get the distance between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function distance(a, b) { - return Math.sqrt(Vec2Utils.distanceSq(a, b)); - }; - Vec2Utils.distanceSq = /** - * Get the distance squared between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function distanceSq(a, b) { - return ((a.x - b.x) * (a.x - b.x)) + ((a.y - b.y) * (a.y - b.y)); - }; - Vec2Utils.project = /** - * Project two 2D vectors onto another vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function project(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var amt = a.dot(b) / b.lengthSq(); - if(amt != 0) { - out.setTo(amt * b.x, amt * b.y); - } - return out; - }; - Vec2Utils.projectUnit = /** - * Project this vector onto a vector of unit length. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function projectUnit(a, b, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var amt = a.dot(b); - if(amt != 0) { - out.setTo(amt * b.x, amt * b.y); - } - return out; - }; - Vec2Utils.normalRightHand = /** - * Right-hand normalize (make unit length) a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function normalRightHand(a, out) { - if (typeof out === "undefined") { out = this; } - return out.setTo(a.y * -1, a.x); - }; - Vec2Utils.normalize = /** - * Normalize (make unit length) a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function normalize(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var m = a.length(); - if(m != 0) { - out.setTo(a.x / m, a.y / m); - } - return out; - }; - Vec2Utils.dot = /** - * The dot product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function dot(a, b) { - return ((a.x * b.x) + (a.y * b.y)); - }; - Vec2Utils.cross = /** - * The cross product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function cross(a, b) { - return ((a.x * b.y) - (a.y * b.x)); - }; - Vec2Utils.angle = /** - * The angle between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function angle(a, b) { - return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y); - }; - Vec2Utils.angleSq = /** - * The angle squared between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - function angleSq(a, b) { - return a.subtract(b).angle(b.subtract(a)); - }; - Vec2Utils.rotate = /** - * Rotate a 2D vector around the origin to the given angle (theta). - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Number} theta The angle of rotation in radians. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - function rotate(a, b, theta, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - var x = a.x - b.x; - var y = a.y - b.y; - return out.setTo(x * Math.cos(theta) - y * Math.sin(theta) + b.x, x * Math.sin(theta) + y * Math.cos(theta) + b.y); - }; - Vec2Utils.clone = /** - * Clone a 2D vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2 that is a copy of the source Vec2. - */ - function clone(a, out) { - if (typeof out === "undefined") { out = new Phaser.Vec2(); } - return out.setTo(a.x, a.y); - }; - return Vec2Utils; - })(); - Phaser.Vec2Utils = Vec2Utils; - /** - * Reflect this vector on an arbitrary axis. - * - * @param {Vec2} axis The vector representing the axis. - * @return {Vec2} This for chaining. - */ - /* - static reflect(axis): Vec2 { - - var x = this.x; - var y = this.y; - this.project(axis).scale(2); - this.x -= x; - this.y -= y; - - return this; - - } - */ - /** - * Reflect this vector on an arbitrary axis (represented by a unit vector) - * - * @param {Vec2} axis The unit vector representing the axis. - * @return {Vec2} This for chaining. - */ - /* - static reflectN(axis): Vec2 { - - var x = this.x; - var y = this.y; - this.projectN(axis).scale(2); - this.x -= x; - this.y -= y; - - return this; - - } - - static getMagnitude(): number { - return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)); - } - */ - })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /** - * Phaser - PhysicsManager - * - * Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding - * all of the physics objects in the world. - */ - (function (Physics) { - var PhysicsManager = (function () { - function PhysicsManager(game, width, height) { - this._length = 0; - this.game = game; - this.gravity = new Phaser.Vec2(); - this.drag = new Phaser.Vec2(); - this.bounce = new Phaser.Vec2(); - this.friction = new Phaser.Vec2(); - this.bounds = new Phaser.Rectangle(0, 0, width, height); - this._distance = new Phaser.Vec2(); - this._tangent = new Phaser.Vec2(); - this._objects = []; - } - PhysicsManager.prototype.add = // Add some sanity checks here + remove method, etc - function (shape) { - this._objects.push(shape); - return shape; - }; - PhysicsManager.prototype.remove = function (shape) { - this._length = this._objects.length; - for(var i = 0; i < this._length; i++) { - if(this._objects[i] === shape) { - this._objects[i] = null; - } - } - }; - PhysicsManager.prototype.update = function () { - this._length = this._objects.length; - for(var i = 0; i < this._length; i++) { - if(this._objects[i]) { - this._objects[i].preUpdate(); - this.updateMotion(this._objects[i]); - this.collideWorld(this._objects[i]); - for(var x = 0; x < this._length; x++) { - if(this._objects[x] && this._objects[x] !== this._objects[i]) { - //this.collideShapes(this._objects[i], this._objects[x]); - var r = this.NEWseparate(this._objects[i], this._objects[x]); - //console.log('sep', r); - } - } - } - } - }; - PhysicsManager.prototype.render = function () { - // iterate through the objects here, updating and colliding - for(var i = 0; i < this._length; i++) { - if(this._objects[i]) { - this._objects[i].render(this.game.stage.context); - } - } - }; - PhysicsManager.prototype.updateMotion = function (shape) { - if(shape.physics.moves == false) { - return; - } - /* - 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; - */ - this._velocityDelta = (this.computeVelocity(shape.physics.velocity.x, shape.physics.gravity.x, shape.physics.acceleration.x, shape.physics.drag.x) - shape.physics.velocity.x) / 2; - shape.physics.velocity.x += this._velocityDelta; - this._delta = shape.physics.velocity.x * this.game.time.elapsed; - shape.physics.velocity.x += this._velocityDelta; - shape.position.x += this._delta; - this._velocityDelta = (this.computeVelocity(shape.physics.velocity.y, shape.physics.gravity.y, shape.physics.acceleration.y, shape.physics.drag.y) - shape.physics.velocity.y) / 2; - shape.physics.velocity.y += this._velocityDelta; - this._delta = shape.physics.velocity.y * this.game.time.elapsed; - shape.physics.velocity.y += this._velocityDelta; - shape.position.y += this._delta; - }; - PhysicsManager.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. - */ - function (velocity, gravity, acceleration, drag, max) { - if (typeof gravity === "undefined") { gravity = 0; } - if (typeof acceleration === "undefined") { acceleration = 0; } - if (typeof drag === "undefined") { drag = 0; } - if (typeof max === "undefined") { max = 10000; } - if(acceleration !== 0) { - velocity += (acceleration + gravity) * this.game.time.elapsed; - } else if(drag !== 0) { - this._drag = drag * this.game.time.elapsed; - if(velocity - this._drag > 0) { - velocity = velocity - this._drag; - } else if(velocity + this._drag < 0) { - velocity += this._drag; - } else { - velocity = 0; - } - velocity += gravity; - } - if((velocity != 0) && (max != 10000)) { - if(velocity > max) { - velocity = max; - } else if(velocity < -max) { - velocity = -max; - } - } - return velocity; - }; - PhysicsManager.prototype.collideShapes = function (shapeA, shapeB) { - if(shapeA.physics.immovable && shapeB.physics.immovable) { - return; - } - this._distance.setTo(0, 0); - this._tangent.setTo(0, 0); - // Simple bounds check first - if(Phaser.RectangleUtils.intersects(shapeA.bounds, shapeB.bounds)) { - // Collide on the x-axis - if(shapeA.physics.velocity.x > 0 && shapeA.bounds.right > shapeB.bounds.x && shapeA.bounds.right <= shapeB.bounds.right) { - // The right side of ShapeA hit the left side of ShapeB - this._distance.x = shapeB.bounds.x - shapeA.bounds.right; - if(this._distance.x != 0) { - this._tangent.x = -1; - } - } else if(shapeA.physics.velocity.x < 0 && shapeA.bounds.x < shapeB.bounds.right && shapeA.bounds.x >= shapeB.bounds.x) { - // The left side of ShapeA hit the right side of ShapeB - this._distance.x = shapeB.bounds.right - shapeA.bounds.x; - if(this._distance.x != 0) { - this._tangent.x = 1; - } - } - // Collide on the y-axis - if(shapeA.physics.velocity.y < 0 && shapeA.bounds.y < shapeB.bounds.bottom && shapeA.bounds.y > shapeB.bounds.y) { - console.log('top A -> bot B'); - // The top of ShapeA hit the bottom of ShapeB - this._distance.y = shapeB.bounds.bottom - shapeA.bounds.y; - console.log(shapeA.bounds, shapeB.bounds, this._distance.y); - if(this._distance.y != 0) { - this._tangent.y = 1; - } - } else if(shapeA.physics.velocity.y > 0 && shapeA.bounds.bottom > shapeB.bounds.y && shapeA.bounds.bottom < shapeB.bounds.bottom) { - // The bottom of ShapeA hit the top of ShapeB - this._distance.y = shapeB.bounds.y - shapeA.bounds.bottom; - if(this._distance.y != 0) { - this._tangent.y = -1; - } - } - // Separate - if(this._distance.equals(0) == false) { - //this.separate(shapeA, shapeB, this._distance, this._tangent); - } - } - }; - PhysicsManager.prototype.NEWseparate = /** - * 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 (object1, object2) { - var separatedX = this.separateSpriteToSpriteX(object1, object2); - var separatedY = this.separateSpriteToSpriteY(object1, object2); - return separatedX || separatedY; - }; - PhysicsManager.prototype.checkHullIntersection = function (shape1, shape2) { - //if ((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.bounds.width) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) - // maybe not bounds.width? - if((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.hullWidth) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) { - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.separateSpriteToSpriteX = /** - * 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 (object1, object2) { - // Can't separate two immovable objects - if(object1.physics.immovable && object2.physics.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - if(object1.physics.shape.deltaX != object2.physics.shape.deltaX) { - if(Phaser.RectangleUtils.intersects(object1.physics.shape.bounds, object2.physics.shape.bounds)) { - //var maxOverlap: number = object1.physics.shape.deltaXAbs + object2.physics.shape.deltaXAbs + Collision.OVERLAP_BIAS; - var maxOverlap = object1.physics.shape.deltaXAbs + object2.physics.shape.deltaXAbs + 4; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object1.physics.shape.deltaX > object2.physics.shape.deltaX) { - overlap = object1.physics.shape.bounds.right - object2.physics.shape.bounds.x; - if((overlap > maxOverlap) || !(object1.physics.allowCollisions & Phaser.Types.RIGHT) || !(object2.physics.allowCollisions & Phaser.Types.LEFT)) { - overlap = 0; - } else { - object1.physics.touching |= Phaser.Types.RIGHT; - object2.physics.touching |= Phaser.Types.LEFT; - } - } else if(object1.physics.shape.deltaX < object2.physics.shape.deltaX) { - overlap = object1.physics.shape.bounds.x - object2.physics.shape.bounds.width - object2.physics.shape.bounds.x; - if((-overlap > maxOverlap) || !(object1.physics.allowCollisions & Phaser.Types.LEFT) || !(object2.physics.allowCollisions & Phaser.Types.RIGHT)) { - overlap = 0; - } else { - object1.physics.touching |= Phaser.Types.LEFT; - object2.physics.touching |= Phaser.Types.RIGHT; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - var obj1Velocity = object1.physics.velocity.x; - var obj2Velocity = object2.physics.velocity.x; - if(!object1.physics.immovable && !object2.physics.immovable) { - overlap *= 0.5; - object1.physics.shape.position.x = object1.physics.shape.position.x - overlap; - object2.physics.shape.position.x += overlap; - var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.physics.mass) / object1.physics.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.physics.mass) / object2.physics.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; - obj1NewVelocity -= average; - obj2NewVelocity -= average; - object1.physics.velocity.x = average + obj1NewVelocity * object1.physics.bounce.x; - object2.physics.velocity.x = average + obj2NewVelocity * object2.physics.bounce.x; - } else if(!object1.physics.immovable) { - overlap *= 2; - object1.physics.shape.position.x -= overlap; - object1.physics.velocity.x = obj2Velocity - obj1Velocity * object1.physics.bounce.x; - } else if(!object2.physics.immovable) { - overlap *= 2; - object2.physics.shape.position.x += overlap; - object2.physics.velocity.x = obj1Velocity - obj2Velocity * object2.physics.bounce.x; - } - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.separateSpriteToSpriteY = /** - * 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 (object1, object2) { - // Can't separate two immovable objects - if(object1.physics.immovable && object2.physics.immovable) { - return false; - } - // First, get the two object deltas - var overlap = 0; - if(object1.physics.shape.deltaY != object2.physics.shape.deltaY) { - if(Phaser.RectangleUtils.intersects(object1.physics.shape.bounds, object2.physics.shape.bounds)) { - // This is the only place to use the DeltaAbs values - //var maxOverlap: number = object1.physics.shape.deltaYAbs + object2.physics.shape.deltaYAbs + Phaser.Types.OVERLAP_BIAS; - var maxOverlap = object1.physics.shape.deltaYAbs + object2.physics.shape.deltaYAbs + 4; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(object1.physics.shape.deltaY > object2.physics.shape.deltaY) { - overlap = object1.physics.shape.bounds.bottom - object2.physics.shape.bounds.y; - if((overlap > maxOverlap) || !(object1.physics.allowCollisions & Phaser.Types.DOWN) || !(object2.physics.allowCollisions & Phaser.Types.UP)) { - overlap = 0; - } else { - object1.physics.touching |= Phaser.Types.DOWN; - object2.physics.touching |= Phaser.Types.UP; - } - } else if(object1.physics.shape.deltaY < object2.physics.shape.deltaY) { - overlap = object1.physics.shape.bounds.y - object2.physics.shape.bounds.height - object2.physics.shape.bounds.y; - if((-overlap > maxOverlap) || !(object1.physics.allowCollisions & Phaser.Types.UP) || !(object2.physics.allowCollisions & Phaser.Types.DOWN)) { - overlap = 0; - } else { - object1.physics.touching |= Phaser.Types.UP; - object2.physics.touching |= Phaser.Types.DOWN; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(overlap != 0) { - var obj1Velocity = object1.physics.velocity.y; - var obj2Velocity = object2.physics.velocity.y; - if(!object1.physics.immovable && !object2.physics.immovable) { - overlap *= 0.5; - object1.physics.shape.position.y = object1.physics.shape.position.y - overlap; - object2.physics.shape.position.y += overlap; - var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.physics.mass) / object1.physics.mass) * ((obj2Velocity > 0) ? 1 : -1); - var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.physics.mass) / object2.physics.mass) * ((obj1Velocity > 0) ? 1 : -1); - var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; - obj1NewVelocity -= average; - obj2NewVelocity -= average; - object1.physics.velocity.y = average + obj1NewVelocity * object1.physics.bounce.y; - object2.physics.velocity.y = average + obj2NewVelocity * object2.physics.bounce.y; - } else if(!object1.physics.immovable) { - overlap *= 2; - object1.physics.shape.position.y -= overlap; - object1.physics.velocity.y = obj2Velocity - obj1Velocity * object1.physics.bounce.y; - // This is special case code that handles things like horizontal moving platforms you can ride - if(object2.active && object2.physics.moves && (object1.physics.shape.deltaY > object2.physics.shape.deltaY)) { - object1.physics.shape.position.x += object2.physics.shape.position.x - object2.physics.shape.oldPosition.x; - } - } else if(!object2.physics.immovable) { - overlap *= 2; - object2.physics.shape.position.y += overlap; - object2.physics.velocity.y = obj1Velocity - obj2Velocity * object2.physics.bounce.y; - // This is special case code that handles things like horizontal moving platforms you can ride - if(object1.active && object1.physics.moves && (object1.physics.shape.deltaY < object2.physics.shape.deltaY)) { - object2.physics.shape.position.x += object1.physics.shape.position.x - object1.physics.shape.oldPosition.x; - } - } - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.separate = function (shapeA, shapeB, distance, tangent) { - if(tangent.x == 1) { - console.log('1 The left side of ShapeA hit the right side of ShapeB', Math.floor(distance.x)); - shapeA.physics.touching |= Phaser.Types.LEFT; - shapeB.physics.touching |= Phaser.Types.RIGHT; - } else if(tangent.x == -1) { - console.log('2 The right side of ShapeA hit the left side of ShapeB', Math.floor(distance.x)); - shapeA.physics.touching |= Phaser.Types.RIGHT; - shapeB.physics.touching |= Phaser.Types.LEFT; - } - if(tangent.y == 1) { - console.log('3 The top of ShapeA hit the bottom of ShapeB', Math.floor(distance.y)); - shapeA.physics.touching |= Phaser.Types.UP; - shapeB.physics.touching |= Phaser.Types.DOWN; - } else if(tangent.y == -1) { - console.log('4 The bottom of ShapeA hit the top of ShapeB', Math.floor(distance.y)); - shapeA.physics.touching |= Phaser.Types.DOWN; - shapeB.physics.touching |= Phaser.Types.UP; - } - // only apply collision response forces if the object is travelling into, and not out of, the collision - var dot = Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent); - if(dot < 0) { - console.log('in to', dot); - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } else { - console.log('out of', dot); - } - shapeA.position.x += Math.floor(distance.x); - //shapeA.bounds.x += Math.floor(distance.x); - shapeA.position.y += Math.floor(distance.y); - //shapeA.bounds.y += distance.y; - console.log('------------------------------------------------'); - }; - PhysicsManager.prototype.collideWorld = function (shape) { - // Collide on the x-axis - this._distance.x = shape.world.bounds.x - (shape.position.x - shape.bounds.halfWidth); - if(0 < this._distance.x) { - // Hit Left - this._tangent.setTo(1, 0); - this.separateXWall(shape, this._distance, this._tangent); - } else { - this._distance.x = (shape.position.x + shape.bounds.halfWidth) - shape.world.bounds.right; - if(0 < this._distance.x) { - // Hit Right - this._tangent.setTo(-1, 0); - this._distance.reverse(); - this.separateXWall(shape, this._distance, this._tangent); - } - } - // Collide on the y-axis - this._distance.y = shape.world.bounds.y - (shape.position.y - shape.bounds.halfHeight); - if(0 < this._distance.y) { - // Hit Top - this._tangent.setTo(0, 1); - this.separateYWall(shape, this._distance, this._tangent); - } else { - this._distance.y = (shape.position.y + shape.bounds.halfHeight) - shape.world.bounds.bottom; - if(0 < this._distance.y) { - // Hit Bottom - this._tangent.setTo(0, -1); - this._distance.reverse(); - this.separateYWall(shape, this._distance, this._tangent); - } - } - }; - PhysicsManager.prototype.separateX = function (shapeA, shapeB, distance, tangent) { - if(tangent.x == 1) { - console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.LEFT; - shapeB.physics.touching |= Phaser.Types.RIGHT; - } else { - console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.RIGHT; - shapeB.physics.touching |= Phaser.Types.LEFT; - } - // collision edges - //shapeA.oH = tangent.x; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - } - shapeA.position.x += distance.x; - shapeA.bounds.x += distance.x; - }; - PhysicsManager.prototype.separateY = function (shapeA, shapeB, distance, tangent) { - if(tangent.y == 1) { - console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.UP; - shapeB.physics.touching |= Phaser.Types.DOWN; - } else { - console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.DOWN; - shapeB.physics.touching |= Phaser.Types.UP; - } - // collision edges - //shapeA.oV = tangent.y; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } - shapeA.position.y += distance.y; - shapeA.bounds.y += distance.y; - }; - PhysicsManager.prototype.separateXWall = function (shapeA, distance, tangent) { - if(tangent.x == 1) { - console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.LEFT; - } else { - console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.RIGHT; - } - // collision edges - //shapeA.oH = tangent.x; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - } - shapeA.position.x += distance.x; - }; - PhysicsManager.prototype.separateYWall = function (shapeA, distance, tangent) { - if(tangent.y == 1) { - console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.UP; - } else { - console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.DOWN; - } - // collision edges - //shapeA.oV = tangent.y; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } - shapeA.position.y += distance.y; - }; - PhysicsManager.prototype.OLDseparate = function (shape, distance, tangent) { - // collision edges - //shape.oH = tangent.x; - //shape.oV = tangent.y; - // Velocity (move to temp vars) - // was vx/vy - var velocity = Phaser.Vec2Utils.subtract(shape.position, shape.oldPosition); - // was dp - var dot = Phaser.Vec2Utils.dot(shape.physics.velocity, tangent); - // project velocity onto the collision normal - // was nx/ny - tangent.multiplyByScalar(dot); - // was tx/ty (tangent velocity?) - var tangentVelocity = Phaser.Vec2Utils.subtract(velocity, tangent); - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(dot < 0) { - // Apply horizontal bounce - if(distance.x != 0) { - if(shape.physics.bounce.x > 0) { - shape.physics.velocity.x *= -(shape.physics.bounce.x); - } else { - shape.physics.velocity.x = 0; - } - } - // Apply vertical bounce - if(distance.y != 0) { - if(shape.physics.bounce.y > 0) { - shape.physics.velocity.y *= -(shape.physics.bounce.y); - } else { - shape.physics.velocity.y = 0; - } - } - } else { - // moving out of collision - } - // project object out of collision - //console.log('proj out', distance.x, distance.y,'dot',dot); - shape.position.add(distance); - }; - return PhysicsManager; - })(); - Physics.PhysicsManager = PhysicsManager; + var Particle = (function (_super) { + __extends(Particle, _super); /** - * 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. + * Instantiate a new particle. Like Sprite, all meaningful creation + * happens during loadGraphic() or makeGraphic() or whatever. */ - /* - public overlap(object1: Basic = null, object2: Basic = null, notifyCallback = null, processCallback = null, context = null): bool { - - if (object1 == null) - { - object1 = this._game.world.group; - } - - if (object2 == object1) - { - object2 = null; - } - - QuadTree.divisions = this._game.world.worldDivisions; - - var quadTree: QuadTree = new 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: bool = quadTree.execute(); - - quadTree.destroy(); - - quadTree = null; - - return result; - + 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. */ - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /** - * Phaser - Physics - AABB - */ - (function (Physics) { - var AABB = (function () { - function AABB(game, sprite, x, y, width, height) { - this.game = game; - this.world = game.world.physics; - if(sprite !== null) { - this.sprite = sprite; - this.scale = Phaser.Vec2Utils.clone(this.sprite.scale); - } else { - this.sprite = null; - this.physics = null; - this.scale = new Phaser.Vec2(1, 1); - } - this.bounds = new Phaser.Rectangle(x + Math.round(width / 2), y + Math.round(height / 2), width, height); - this.position = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Phaser.Vec2(0, 0); + function () { + //lifespan behavior + if(this.lifespan <= 0) { + return; } - AABB.prototype.preUpdate = function () { - this.oldPosition.copyFrom(this.position); - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - if(this.sprite) { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - // Update scale / dimensions - if(Phaser.Vec2Utils.equals(this.scale, this.sprite.scale) == false) { - this.scale.copyFrom(this.sprite.scale); - this.bounds.width = this.sprite.width; - this.bounds.height = this.sprite.height; - } + this.lifespan -= this.game.time.elapsed; + if(this.lifespan <= 0) { + this.kill(); + } + //simpler bounce/spin behavior for now + if(this.body.touching) { + if(this.body.angularVelocity != 0) { + this.body.angularVelocity = -this.body.angularVelocity; } - }; - AABB.prototype.update = function () { - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - }; - AABB.prototype.setSize = function (width, height) { - this.bounds.width = width; - this.bounds.height = height; - }; - AABB.prototype.render = function (context) { - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.strokeRect(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight, this.bounds.width, this.bounds.height); - context.stroke(); - context.closePath(); - // center point - context.fillStyle = 'rgb(0,255,0)'; - context.fillRect(this.position.x, this.position.y, 2, 2); - if(this.physics.touching & Phaser.Types.LEFT) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.RIGHT) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.UP) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.DOWN) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - }; - Object.defineProperty(AABB.prototype, "hullWidth", { - get: function () { - if(this.deltaX > 0) { - return this.bounds.width + this.deltaX; - } else { - return this.bounds.width - this.deltaX; + } + if(this.body.acceleration.y > 0)//special behavior for particles with gravity + { + if(this.body.touching & Phaser.Types.FLOOR) { + this.body.drag.x = this.friction; + if(!(this.body.wasTouching & Phaser.Types.FLOOR)) { + if(this.body.velocity.y < -this.body.bounce.y * 10) { + if(this.body.angularVelocity != 0) { + this.body.angularVelocity *= -this.body.bounce.y; + } + } else { + this.body.velocity.y = 0; + this.body.angularVelocity = 0; + } } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullHeight", { - get: function () { - if(this.deltaY > 0) { - return this.bounds.height + this.deltaY; - } else { - return this.bounds.height - this.deltaY; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullX", { - get: function () { - if(this.position.x < this.oldPosition.x) { - return this.position.x; - } else { - return this.oldPosition.x; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullY", { - get: function () { - if(this.position.y < this.oldPosition.y) { - return this.position.y; - } else { - return this.oldPosition.y; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaXAbs", { - get: function () { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaYAbs", { - get: function () { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaX", { - get: function () { - return this.position.x - this.oldPosition.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaY", { - get: function () { - return this.position.y - this.oldPosition.y; - }, - enumerable: true, - configurable: true - }); - return AABB; - })(); - Physics.AABB = AABB; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; + } else { + this.body.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 - Emitter +* +* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for +* continuous effects like rain and fire. All it really does is launch Particle objects out +* at set intervals, and fixes their positions and velocities accorindgly. +*/ +var Phaser; +(function (Phaser) { + var Emitter = (function (_super) { + __extends(Emitter, _super); + /** + * Creates a new Emitter object at a specific position. + * Does NOT automatically generate or attach particles! + * + * @param x {number} The X position of the emitter. + * @param y {number} The Y position of the emitter. + * @param [size] {number} Specifies a maximum capacity for this emitter. + */ + function Emitter(game, x, y, size) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof size === "undefined") { size = 0; } + _super.call(this, game, size); + this.x = x; + this.y = y; + this.width = 0; + this.height = 0; + this.minParticleSpeed = new Phaser.Vec2(-100, -100); + this.maxParticleSpeed = new Phaser.Vec2(100, 100); + this.minRotation = -360; + this.maxRotation = 360; + this.gravity = 0; + this.particleClass = null; + this.particleDrag = new Phaser.Vec2(); + this.frequency = 0.1; + this.lifespan = 3; + this.bounce = 0; + this._quantity = 0; + this._counter = 0; + this._explode = true; + this.on = false; + } + 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.texture.loadImage(graphics); + } + } + if(collide > 0) { + particle.body.allowCollisions = Phaser.Types.ANY; + particle.body.type = Phaser.Types.BODY_DYNAMIC; + particle.width *= collide; + particle.height *= collide; + } else { + particle.body.allowCollisions = Phaser.Types.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; + this.alive = false; + this.exists = false; + }; + Emitter.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; + }; + 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.body.bounce.setTo(this.bounce, this.bounce); + Phaser.SpriteUtils.reset(particle, 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.body.velocity.x = this.minParticleSpeed.x + this.game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x); + } else { + particle.body.velocity.x = this.minParticleSpeed.x; + } + if(this.minParticleSpeed.y != this.maxParticleSpeed.y) { + particle.body.velocity.y = this.minParticleSpeed.y + this.game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y); + } else { + particle.body.velocity.y = this.minParticleSpeed.y; + } + particle.body.acceleration.y = this.gravity; + if(this.minRotation != this.maxRotation && this.minRotation !== 0 && this.maxRotation !== 0) { + particle.body.angularVelocity = this.minRotation + this.game.math.random() * (this.maxRotation - this.minRotation); + } else { + particle.body.angularVelocity = this.minRotation; + } + if(particle.body.angularVelocity != 0) { + particle.angle = this.game.math.random() * 360 - 180; + } + particle.body.drag.x = this.particleDrag.x; + particle.body.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) { + this.x = object.body.bounds.halfWidth - (this.width >> 1); + this.y = object.body.bounds.halfHeight - (this.height >> 1); + }; + return Emitter; + })(Phaser.Group); + Phaser.Emitter = Emitter; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - ScrollRegion +* +* Creates a scrolling region within a ScrollZone. +* It is scrolled via the scrollSpeed.x/y properties. +*/ +var Phaser; +(function (Phaser) { + var ScrollRegion = (function () { + /** + * ScrollRegion constructor + * Create a new ScrollRegion. + * + * @param x {number} X position in world coordinate. + * @param y {number} Y position in world coordinate. + * @param width {number} Width of this object. + * @param height {number} Height of this object. + * @param speedX {number} X-axis scrolling speed. + * @param speedY {number} Y-axis scrolling speed. + */ + function ScrollRegion(x, y, width, height, speedX, speedY) { + this._anchorWidth = 0; + this._anchorHeight = 0; + this._inverseWidth = 0; + this._inverseHeight = 0; + /** + * Will this region be rendered? (default to true) + * @type {boolean} + */ + this.visible = true; + // Our seamless scrolling quads + this._A = new Phaser.Rectangle(x, y, width, height); + this._B = new Phaser.Rectangle(x, y, width, height); + this._C = new Phaser.Rectangle(x, y, width, height); + this._D = new Phaser.Rectangle(x, y, width, height); + this._scroll = new Phaser.Vec2(); + this._bounds = new Phaser.Rectangle(x, y, width, height); + this.scrollSpeed = new Phaser.Vec2(speedX, speedY); + } + ScrollRegion.prototype.update = /** + * Update region scrolling with tick time. + * @param delta {number} Elapsed time since last update. + */ + function (delta) { + this._scroll.x += this.scrollSpeed.x; + this._scroll.y += this.scrollSpeed.y; + if(this._scroll.x > this._bounds.right) { + this._scroll.x = this._bounds.x; + } + if(this._scroll.x < this._bounds.x) { + this._scroll.x = this._bounds.right; + } + if(this._scroll.y > this._bounds.bottom) { + this._scroll.y = this._bounds.y; + } + if(this._scroll.y < this._bounds.y) { + this._scroll.y = this._bounds.bottom; + } + // Anchor Dimensions + this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; + this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; + if(this._anchorWidth > this._bounds.width) { + this._anchorWidth = this._bounds.width; + } + if(this._anchorHeight > this._bounds.height) { + this._anchorHeight = this._bounds.height; + } + this._inverseWidth = this._bounds.width - this._anchorWidth; + this._inverseHeight = this._bounds.height - this._anchorHeight; + // Rectangle A + this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); + // Rectangle B + this._B.y = this._scroll.y; + this._B.width = this._inverseWidth; + this._B.height = this._anchorHeight; + // Rectangle C + this._C.x = this._scroll.x; + this._C.width = this._anchorWidth; + this._C.height = this._inverseHeight; + // Rectangle D + this._D.width = this._inverseWidth; + this._D.height = this._inverseHeight; + }; + ScrollRegion.prototype.render = /** + * Render this region to specific context. + * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. + * @param texture {object} The texture to be rendered. + * @param dx {number} X position in world coordinate. + * @param dy {number} Y position in world coordinate. + * @param width {number} Width of this region to be rendered. + * @param height {number} Height of this region to be rendered. + */ + function (context, texture, dx, dy, dw, dh) { + if(this.visible == false) { + return; + } + // dx/dy are the world coordinates to render the FULL ScrollZone into. + // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. + this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); + this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); + this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); + this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); + //context.fillStyle = 'rgb(255,255,255)'; + //context.font = '18px Arial'; + //context.fillText('RectangleA: ' + this._A.toString(), 32, 450); + //context.fillText('RectangleB: ' + this._B.toString(), 32, 480); + //context.fillText('RectangleC: ' + this._C.toString(), 32, 510); + //context.fillText('RectangleD: ' + this._D.toString(), 32, 540); + }; + ScrollRegion.prototype.crop = /** + * Crop part of the texture and render it to the given context. + * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. + * @param texture {object} Texture to be rendered. + * @param srcX {number} Target region top-left x coordinate in the texture. + * @param srcX {number} Target region top-left y coordinate in the texture. + * @param srcW {number} Target region width in the texture. + * @param srcH {number} Target region height in the texture. + * @param destX {number} Render region top-left x coordinate in the context. + * @param destX {number} Render region top-left y coordinate in the context. + * @param destW {number} Target region width in the context. + * @param destH {number} Target region height in the context. + * @param offsetX {number} X offset to the context. + * @param offsetY {number} Y offset to the context. + */ + function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { + offsetX += destX; + offsetY += destY; + if(srcW > (destX + destW) - offsetX) { + srcW = (destX + destW) - offsetX; + } + if(srcH > (destY + destH) - offsetY) { + srcH = (destY + destH) - offsetY; + } + srcX = Math.floor(srcX); + srcY = Math.floor(srcY); + srcW = Math.floor(srcW); + srcH = Math.floor(srcH); + offsetX = Math.floor(offsetX + this._bounds.x); + offsetY = Math.floor(offsetY + this._bounds.y); + if(srcW > 0 && srcH > 0) { + context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); + } + }; + return ScrollRegion; + })(); + Phaser.ScrollRegion = ScrollRegion; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - 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, key); + this.type = Phaser.Types.SCROLLZONE; + this.render = game.renderer.renderScrollZone; + this.regions = []; + if(this.texture.loaded) { + if(width > this.width || height > this.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.width || height < this.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.createRepeatingTexture = /** + * Create repeating texture with _texture, and store it into the _dynamicTexture. + * Used to create texture when texture image is small than size of the zone. + */ + function (regionWidth, regionHeight) { + // Work out how many we'll need of the source image to make it tile properly + var tileWidth = Math.ceil(this.width / regionWidth) * regionWidth; + var tileHeight = Math.ceil(this.height / regionHeight) * regionHeight; + var dt = new Phaser.DynamicTexture(this.game, tileWidth, tileHeight); + dt.context.rect(0, 0, tileWidth, tileHeight); + dt.context.fillStyle = dt.context.createPattern(this.texture.imageTexture, "repeat"); + dt.context.fill(); + this.texture.loadDynamicTexture(dt); + }; + return ScrollZone; + })(Phaser.Sprite); + Phaser.ScrollZone = ScrollZone; +})(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.body.bounds.x < 0 || object.body.bounds.x > this.widthInPixels || object.body.bounds.y < 0 || object.body.bounds.bottom > this.heightInPixels) { + return; + } + // What tiles do we need to check against? + this._tempTileX = this._game.math.snapToFloor(object.body.bounds.x, this.tileWidth) / this.tileWidth; + this._tempTileY = this._game.math.snapToFloor(object.body.bounds.y, this.tileHeight) / this.tileHeight; + this._tempTileW = (this._game.math.snapToCeil(object.body.bounds.width, this.tileWidth) + this.tileWidth) / this.tileWidth; + this._tempTileH = (this._game.math.snapToCeil(object.body.bounds.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.Physics.PhysicsManager.TILE_OVERLAP = false; + for(var r = 0; r < this._tempTileBlock.length; r++) { + if(this._game.world.physics.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.Types.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 = Phaser.Types.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.Types.ANY) { + this.collideLeft = true; + this.collideRight = true; + this.collideUp = true; + this.collideDown = true; + return; + } + if(collision & Phaser.Types.LEFT || collision & Phaser.Types.WALL) { + this.collideLeft = true; + } + if(collision & Phaser.Types.RIGHT || collision & Phaser.Types.WALL) { + this.collideRight = true; + } + if(collision & Phaser.Types.UP || collision & Phaser.Types.CEILING) { + this.collideUp = true; + } + if(collision & Phaser.Types.DOWN || collision & Phaser.Types.CEILING) { + this.collideDown = true; + } + }; + Tile.prototype.resetCollision = /** + * Reset collision status flags. + */ + function () { + this.allowCollisions = Phaser.Types.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 () { + /** + * 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; } + /** + * Tilemap collision callback. + * @type {function} + */ + this.collisionCallback = null; + this.game = game; + this.type = Phaser.Types.TILEMAP; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; + this.tiles = []; + this.layers = []; + this.cameraBlacklist = []; + this.mapFormat = format; + switch(format) { + case Tilemap.FORMAT_CSV: + this.parseCSV(game.cache.getText(mapData), key, tileWidth, tileHeight); + break; + case Tilemap.FORMAT_TILED_JSON: + this.parseTiledJSON(game.cache.getText(mapData), key); + break; + } + if(this.currentLayer && resizeWorld) { + this.game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); + } + } + Tilemap.FORMAT_CSV = 0; + Tilemap.FORMAT_TILED_JSON = 1; + Tilemap.prototype.update = /** + * Inherited update method. + */ + function () { + }; + Tilemap.prototype.render = /** + * Render this tilemap to a specific camera with specific offset. + * @param camera {Camera} The camera this tilemap will be rendered to. + * @param cameraOffsetX {number} X offset of the camera. + * @param cameraOffsetY {number} Y offset of the camera. + */ + function (camera, cameraOffsetX, cameraOffsetY) { + if(this.cameraBlacklist.indexOf(camera.ID) == -1) { + // Loop through the layers + for(var i = 0; i < this.layers.length; i++) { + this.layers[i].render(camera, cameraOffsetX, cameraOffsetY); + } + } + }; + Tilemap.prototype.parseCSV = /** + * Parset csv map data and generate tiles. + * @param data {string} CSV map data. + * @param key {string} Asset key for tileset image. + * @param tileWidth {number} Width of its tile. + * @param tileHeight {number} Height of its tile. + */ + function (data, key, tileWidth, tileHeight) { + var layer = new Phaser.TilemapLayer(this.game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); + // Trim any rogue whitespace from the data + data = data.trim(); + var rows = data.split("\n"); + for(var i = 0; i < rows.length; i++) { + var column = rows[i].split(","); + if(column.length > 0) { + layer.addColumn(column); + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.parseTiledJSON = /** + * Parset JSON map data and generate tiles. + * @param data {string} JSON map data. + * @param key {string} Asset key for tileset image. + */ + function (data, key) { + // Trim any rogue whitespace from the data + data = data.trim(); + var json = JSON.parse(data); + for(var i = 0; i < json.layers.length; i++) { + var layer = new Phaser.TilemapLayer(this.game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); + layer.alpha = json.layers[i].opacity; + layer.visible = json.layers[i].visible; + layer.tileMargin = json.tilesets[0].margin; + layer.tileSpacing = json.tilesets[0].spacing; + var c = 0; + var row; + for(var t = 0; t < json.layers[i].data.length; t++) { + if(c == 0) { + row = []; + } + row.push(json.layers[i].data[t]); + c++; + if(c == json.layers[i].width) { + layer.addColumn(row); + c = 0; + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + } + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.generateTiles = /** + * Create tiles of given quantity. + * @param qty {number} Quentity of tiles to be generated. + */ + function (qty) { + for(var i = 0; i < qty; i++) { + this.tiles.push(new Phaser.Tile(this.game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); + } + }; + Object.defineProperty(Tilemap.prototype, "widthInPixels", { + get: function () { + return this.currentLayer.widthInPixels; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tilemap.prototype, "heightInPixels", { + get: function () { + return this.currentLayer.heightInPixels; + }, + enumerable: true, + configurable: true + }); + Tilemap.prototype.setCollisionCallback = // Tile Collision + /** + * Set callback to be called when this tilemap collides. + * @param context {object} Callback will be called with this context. + * @param callback {function} Callback function. + */ + function (context, callback) { + this.collisionCallbackContext = context; + this.collisionCallback = callback; + }; + Tilemap.prototype.setCollisionRange = /** + * Set collision configs of tiles in a range index. + * @param start {number} First index of tiles. + * @param end {number} Last index of tiles. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + function (start, end, collision, resetCollisions, separateX, separateY) { + if (typeof collision === "undefined") { collision = Phaser.Types.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.Types.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.body.type == Phaser.Types.BODY_DYNAMIC && object.exists == true && object.body.allowCollisions != Phaser.Types.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.Tilemap = Tilemap; + // Set current layer + // Set layer order? + // Delete tiles of certain type + // Erase tiles + })(Phaser || (Phaser = {})); +/// /// -/// +/// +/// +/// +/// +/// +/// /** * Phaser - GameObjectFactory * @@ -6650,12 +9105,14 @@ var Phaser; * * @param x {number} X position of the new sprite. * @param y {number} Y position of the new sprite. - * @param key {string} Optional, key for the sprite sheet you want it to use. + * @param [key] {string} The image key as defined in the Game.Cache to use as the texture for this sprite + * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) * @returns {Sprite} The newly created sprite object. */ - function (x, y, key) { + function (x, y, key, bodyType) { if (typeof key === "undefined") { key = ''; } - return this._world.group.add(new Phaser.Sprite(this._game, x, y, key)); + if (typeof bodyType === "undefined") { bodyType = Phaser.Types.BODY_DISABLED; } + return this._world.group.add(new Phaser.Sprite(this._game, x, y, key, bodyType)); }; GameObjectFactory.prototype.dynamicTexture = /** * Create a new DynamicTexture with specific size. @@ -6677,27 +9134,15 @@ var Phaser; if (typeof maxSize === "undefined") { maxSize = 0; } return this._world.group.add(new Phaser.Group(this._game, maxSize)); }; - GameObjectFactory.prototype.physicsAABB = /** - * 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} Optional, key for the sprite sheet you want it to use. - * @returns {Sprite} The newly created sprite object. - * WILL NEED TO TRACK A SPRITE - */ - function (x, y, width, height) { - return this._world.physics.add(new Phaser.Physics.AABB(this._game, null, x, y, width, height)); - }; - GameObjectFactory.prototype.scrollZone = /** + GameObjectFactory.prototype.particle = /** * Create a new Particle. * * @return {Particle} The newly created particle object. */ - //public particle(): Particle { - // return new Particle(this._game); - //} - /** + function () { + return new Phaser.Particle(this._game); + }; + GameObjectFactory.prototype.emitter = /** * Create a new Emitter. * * @param x {number} Optional, x position of the emitter. @@ -6705,10 +9150,13 @@ var 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.group.add(new Emitter(this._game, x, y, size)); - //} - /** + 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.group.add(new Phaser.Emitter(this._game, x, y, size)); + }; + GameObjectFactory.prototype.scrollZone = /** * Create a new ScrollZone object with image key, position and size. * * @param key {string} Key to a image you wish this object to use. @@ -6725,7 +9173,7 @@ var Phaser; if (typeof height === "undefined") { height = 0; } return this._world.group.add(new Phaser.ScrollZone(this._game, key, x, y, width, height)); }; - GameObjectFactory.prototype.tween = /** + GameObjectFactory.prototype.tilemap = /** * Create a new Tilemap. * * @param key {string} Key for tileset image. @@ -6736,10 +9184,13 @@ var Phaser; * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { - // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - //} - /** + function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { + if (typeof resizeWorld === "undefined") { resizeWorld = true; } + if (typeof tileWidth === "undefined") { tileWidth = 0; } + if (typeof tileHeight === "undefined") { tileHeight = 0; } + return this._world.group.add(new Phaser.Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + }; + GameObjectFactory.prototype.tween = /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -6758,7 +9209,7 @@ var Phaser; function (sprite) { return this._world.group.add(sprite); }; - GameObjectFactory.prototype.existingScrollZone = /** + GameObjectFactory.prototype.existingEmitter = /** * 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. * @@ -6775,10 +9226,10 @@ var 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); - //} - /** + function (emitter) { + return this._world.group.add(emitter); + }; + GameObjectFactory.prototype.existingScrollZone = /** * 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. * @@ -6788,17 +9239,17 @@ var Phaser; function (scrollZone) { return this._world.group.add(scrollZone); }; - GameObjectFactory.prototype.existingTween = /** + GameObjectFactory.prototype.existingTilemap = /** * Add an existing Tilemap to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - //public existingTilemap(tilemap: Tilemap): Tilemap { - // return this._world.group.add(tilemap); - //} - /** + function (tilemap) { + return this._world.group.add(tilemap); + }; + GameObjectFactory.prototype.existingTween = /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -6812,950 +9263,6 @@ 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; - Types.LEFT = 0x0001; - Types.RIGHT = 0x0010; - Types.UP = 0x0100; - Types.DOWN = 0x1000; - Types.NONE = 0; - Types.CEILING = Types.UP; - Types.FLOOR = Types.DOWN; - Types.WALL = Types.LEFT | Types.RIGHT; - Types.ANY = Types.LEFT | Types.RIGHT | Types.UP | Types.DOWN; - return Types; - })(); - Phaser.Types = Types; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Group -* -* This class is used for organising, updating and sorting game objects. -*/ -var Phaser; -(function (Phaser) { - 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. - * If this value is set it will call a canvas context save and restore before and after the render pass. - * Set to null to disable. - */ - this.globalCompositeOperation = null; - /** - * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. - * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. - * Set to 0 to disable. - */ - this.alpha = 0; - this.game = game; - this.type = Phaser.Types.GROUP; - this.exists = true; - this.visible = true; - this.members = []; - this.length = 0; - this._maxSize = maxSize; - this._marker = 0; - this._sortIndex = null; - this.cameraBlacklist = []; - } - Group.ASCENDING = -1; - Group.DESCENDING = 1; - 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) { - 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; - } - this._sortIndex = null; - }; - Group.prototype.update = /** - * 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; } - 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 = /** - * 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 (renderer, camera) { - if(camera.isHidden(this) == true) { - return; - } - if(this.globalCompositeOperation) { - this.game.stage.context.save(); - this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation; - } - if(this.alpha > 0) { - this._prevAlpha = this.game.stage.context.globalAlpha; - this.game.stage.context.globalAlpha = this.alpha; - } - 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.call(renderer, camera, this._member); - } - } - if(this.alpha > 0) { - this.game.stage.context.globalAlpha = this._prevAlpha; - } - if(this.globalCompositeOperation) { - this.game.stage.context.restore(); - } - }; - Object.defineProperty(Group.prototype, "maxSize", { - get: /** - * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. - */ - function () { - return this._maxSize; - }, - set: /** - * @private - */ - function (Size) { - this._maxSize = Size; - if(this._marker >= this._maxSize) { - this._marker = 0; - } - 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 - 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; - }, - enumerable: true, - configurable: true - }); - Group.prototype.add = /** - * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. - * Group will try to replace a null member of the array first. - * Failing that, Group will add it to the end of the member array, - * assuming there is room for it, and doubling the size of the array if necessary. - * - *

WARNING: If the group has a maxSize that has already been met, - * the object will NOT be added to the group!

- * - * @param {Basic} Object The object you want to add to the group. - * @return {Basic} The same Basic object that was passed in. - */ - function (object) { - //Don't bother adding an object twice. - if(this.members.indexOf(Object) >= 0) { - return object; - } - //First, look for a null entry where we can add the object. - 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; - } - 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; - } else if(this.members.length * 2 <= this._maxSize) { - this.members.length *= 2; - } else { - this.members.length = this._maxSize; - } - } else { - this.members.length *= 2; - } - //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[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. - * - *

If you specified a maximum size for this group (like in Emitter), - * then recycle will employ what we're calling "rotating" recycling. - * Recycle() will first check to see if the group is at capacity yet. - * If group is not yet at capacity, recycle() returns a new object. - * If the group IS at capacity, then recycle() just returns the next object in line.

- * - *

If you did NOT specify a maximum size for this group, - * then recycle() will employ what we're calling "grow-style" recycling. - * Recycle() will return either the first object with exists == false, - * or, finding none, add a new object to the array, - * doubling the size of the array if necessary.

- * - *

WARNING: If this function needs to create a new object, - * and no object class was provided, it will return null - * instead of a valid object!

- * - * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! - * - * @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; } - if(this._maxSize > 0) { - if(this.length < this._maxSize) { - if(objectClass == null) { - return null; - } - return this.add(new objectClass(this.game)); - } else { - this._member = this.members[this._marker++]; - if(this._marker >= this._maxSize) { - this._marker = 0; - } - return this._member; - } - } else { - this._member = this.getFirstAvailable(objectClass); - if(this._member != null) { - return this._member; - } - if(objectClass == null) { - return null; - } - return this.add(new objectClass(this.game)); - } - }; - Group.prototype.remove = /** - * Removes an object from the group. - * - * @param {Basic} object The Basic you want to remove. - * @param {boolean} splice Whether the object should be cut from the array entirely or not. - * - * @return {Basic} The removed object. - */ - function (object, splice) { - if (typeof splice === "undefined") { splice = false; } - this._i = this.members.indexOf(object); - if(this._i < 0 || (this._i >= this.members.length)) { - return null; - } - if(splice) { - this.members.splice(this._i, 1); - this.length--; - } else { - this.members[this._i] = null; - } - return object; - }; - Group.prototype.replace = /** - * Replaces an existing Basic with a new one. - * - * @param {Basic} oldObject The object you want to replace. - * @param {Basic} newObject The new object you want to use instead. - * - * @return {Basic} The new object. - */ - function (oldObject, newObject) { - this._i = this.members.indexOf(oldObject); - if(this._i < 0 || (this._i >= this.members.length)) { - return null; - } - this.members[this._i] = newObject; - return newObject; - }; - Group.prototype.sort = /** - * Call this function to sort the group according to a particular value and order. - * For example, to sort game objects for Zelda-style overlaps you might call - * myGroup.sort("y",Group.ASCENDING) at the bottom of your - * State.update() override. To sort all existing objects after - * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). - * - * @param {string} index The string name of the member variable you want to sort on. Default value is "y". - * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. - */ - function (index, order) { - if (typeof index === "undefined") { index = "y"; } - if (typeof order === "undefined") { order = Group.ASCENDING; } - this._sortIndex = index; - this._sortOrder = order; - this.members.sort(this.sortHandler); - }; - Group.prototype.setAll = /** - * Go through and set the specified variable to the specified value on all members of the group. - * - * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". - * @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; } - 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 { - this._member[variableName] = value; - } - } - } - }; - Group.prototype.callAll = /** - * Go through and call the specified function on all members of the group. - * Currently only works on functions that have no required parameters. - * - * @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; } - 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 { - this._member[functionName](); - } - } - } - }; - Group.prototype.forEach = /** - * @param {function} callback - * @param {boolean} recursive - */ - function (callback, recursive) { - if (typeof recursive === "undefined") { recursive = false; } - 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, this._member); - } - } - } - }; - Group.prototype.forEachAlive = /** - * @param {any} context - * @param {function} callback - * @param {boolean} recursive - */ - function (context, callback, recursive) { - if (typeof recursive === "undefined") { recursive = false; } - 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, this._member); - } - } - } - }; - Group.prototype.getFirstAvailable = /** - * Call this function to retrieve the first object with exists == false in the group. - * This is handy for recycling in general, e.g. respawning enemies. - * - * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. - * - * @return {any} A Basic currently flagged as not existing. - */ - 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; - }; - Group.prototype.getFirstNull = /** - * Call this function to retrieve the first index set to 'null'. - * Returns -1 if no index stores a null object. - * - * @return {number} An int indicating the first null slot in the group. - */ - function () { - this._i = 0; - while(this._i < this.length) { - if(this.members[this._i] == null) { - return this._i; - } else { - this._i++; - } - } - return -1; - }; - Group.prototype.getFirstExtant = /** - * Call this function to retrieve the first object with exists == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as existing. - */ - function () { - 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; - }; - Group.prototype.getFirstAlive = /** - * Call this function to retrieve the first object with dead == false in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as not dead. - */ - function () { - 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; - }; - Group.prototype.getFirstDead = /** - * Call this function to retrieve the first object with dead == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as dead. - */ - function () { - 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; - }; - Group.prototype.countLiving = /** - * Call this function to find out how many members of the group are not dead. - * - * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. - */ - function () { - 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(this._member.exists && this._member.alive) { - this._count++; - } - } - } - return this._count; - }; - Group.prototype.countDead = /** - * Call this function to find out how many members of the group are dead. - * - * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. - */ - function () { - 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(!this._member.alive) { - this._count++; - } - } - } - return this._count; - }; - Group.prototype.getRandom = /** - * Returns a member at random from the group. - * - * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} Length Optional restriction on the number of values you want to randomly select from. - * - * @return {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; - } - return this.game.math.getRandom(this.members, startIndex, length); - }; - Group.prototype.clear = /** - * Remove all instances of Basic subclass (Basic, Block, etc) from the list. - * WARNING: does not destroy() or kill() any of these objects! - */ - function () { - this.length = this.members.length = 0; - }; - Group.prototype.kill = /** - * Calls kill on the group's members and then on the group itself. - */ - function () { - this._i = 0; - while(this._i < this.length) { - this._member = this.members[this._i++]; - if((this._member != null) && this._member.exists) { - this._member.kill(); - } - } - }; - Group.prototype.sortHandler = /** - * Helper function for the sort process. - * - * @param {Basic} Obj1 The first object being sorted. - * @param {Basic} Obj2 The second object being sorted. - * - * @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]) { - return this._sortOrder; - } else if(obj1[this._sortIndex] > obj2[this._sortIndex]) { - return -this._sortOrder; - } - return 0; - }; - return Group; - })(); - Phaser.Group = Group; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - SignalBinding -* -* An object that represents a binding between a Signal and a listener function. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -var Phaser; -(function (Phaser) { - var SignalBinding = (function () { - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - function SignalBinding(signal, listener, isOnce, listenerContext, priority) { - if (typeof priority === "undefined") { priority = 0; } - /** - * If binding is active and should be executed. - * @type boolean - */ - this.active = true; - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - this.params = null; - this._listener = listener; - this._isOnce = isOnce; - this.context = listenerContext; - this._signal = signal; - this.priority = priority || 0; - } - SignalBinding.prototype.execute = /** - * Call listener passing arbitrary parameters. - *

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

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

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

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

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

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

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

- */ - function () { - this.removeAll(); - delete this._bindings; - delete this._prevParams; - }; - Signal.prototype.toString = /** - * @return {string} String representation of the object. - */ - function () { - return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; - }; - return Signal; - })(); - Phaser.Signal = Signal; -})(Phaser || (Phaser = {})); /// /// /** @@ -8898,6 +10405,1111 @@ var Phaser; })(); Phaser.TweenManager = TweenManager; })(Phaser || (Phaser = {})); +/// +/// +/// +/// +/** +* Phaser - CircleUtils +* +* A collection of methods useful for manipulating and comparing Circle objects. +* +* TODO: +*/ +var Phaser; +(function (Phaser) { + var CircleUtils = (function () { + function CircleUtils() { } + CircleUtils.clone = /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. + * @method clone + * @param {Circle} a - The Circle object. + * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} + **/ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Circle(); } + return out.setTo(a.x, a.y, a.diameter); + }; + CircleUtils.contains = /** + * Return true if the given x/y coordinates are within the Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method contains + * @param {Circle} a - The Circle object. + * @param {Number} The X value of the coordinate to test. + * @param {Number} The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function contains(a, x, y) { + //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + return true; + }; + CircleUtils.containsPoint = /** + * Return true if the coordinates of the given Point object are within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method containsPoint + * @param {Circle} a - The Circle object. + * @param {Point} The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsPoint(a, point) { + return CircleUtils.contains(a, point.x, point.y); + }; + CircleUtils.containsCircle = /** + * Return true if the given Circle is contained entirely within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. + * @method containsCircle + * @param {Circle} The Circle object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsCircle(a, b) { + //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + return true; + }; + CircleUtils.distanceBetween = /** + * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) + * @method distanceBetween + * @param {Circle} a - The Circle object. + * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between this Point object and the destination Point object. + **/ + function distanceBetween(a, target, round) { + if (typeof round === "undefined") { round = false; } + var dx = a.x - target.x; + var dy = a.y - target.y; + if(round === true) { + return Math.round(Math.sqrt(dx * dx + dy * dy)); + } else { + return Math.sqrt(dx * dx + dy * dy); + } + }; + CircleUtils.equals = /** + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); + }; + CircleUtils.intersects = /** + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method intersects + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + **/ + function intersects(a, b) { + return (CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); + }; + CircleUtils.circumferencePoint = /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Circle} a - The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + **/ + function circumferencePoint(a, angle, asDegrees, out) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof out === "undefined") { out = new Phaser.Point(); } + if(asDegrees === true) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + return out.setTo(a.x + a.radius * Math.cos(angle), a.y + a.radius * Math.sin(angle)); + }; + CircleUtils.intersectsRectangle = /* + public static boolean intersect(Rectangle r, Circle c) + { + float cx = Math.abs(c.x - r.x - r.halfWidth); + float xDist = r.halfWidth + c.radius; + if (cx > xDist) + return false; + float cy = Math.abs(c.y - r.y - r.halfHeight); + float yDist = r.halfHeight + c.radius; + if (cy > yDist) + return false; + if (cx <= r.halfWidth || cy <= r.halfHeight) + return true; + float xCornerDist = cx - r.halfWidth; + float yCornerDist = cy - r.halfHeight; + float xCornerDistSq = xCornerDist * xCornerDist; + float yCornerDistSq = yCornerDist * yCornerDist; + float maxCornerDistSq = c.radius * c.radius; + return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; + } + */ + function intersectsRectangle(c, r) { + var cx = Math.abs(c.x - r.x - r.halfWidth); + var xDist = r.halfWidth + c.radius; + if(cx > xDist) { + return false; + } + var cy = Math.abs(c.y - r.y - r.halfHeight); + var yDist = r.halfHeight + c.radius; + if(cy > yDist) { + return false; + } + if(cx <= r.halfWidth || cy <= r.halfHeight) { + return true; + } + var xCornerDist = cx - r.halfWidth; + var yCornerDist = cy - r.halfHeight; + var xCornerDistSq = xCornerDist * xCornerDist; + var yCornerDistSq = yCornerDist * yCornerDist; + var maxCornerDistSq = c.radius * c.radius; + return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; + }; + return CircleUtils; + })(); + Phaser.CircleUtils = CircleUtils; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /// + /// + /// + /// + /** + * Phaser - PhysicsManager + * + * Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding + * all of the physics objects in the world. + */ + (function (Physics) { + var PhysicsManager = (function () { + function PhysicsManager(game, width, height) { + this._length = 0; + /** + * @type {number} + */ + this.worldDivisions = 6; + this.game = game; + this.gravity = new Phaser.Vec2(); + this.drag = new Phaser.Vec2(); + this.bounce = new Phaser.Vec2(); + this.angularDrag = 0; + this.bounds = new Phaser.Rectangle(0, 0, width, height); + this._distance = new Phaser.Vec2(); + this._tangent = new Phaser.Vec2(); + this.members = new Phaser.Group(game); + } + PhysicsManager.OVERLAP_BIAS = 4; + PhysicsManager.TILE_OVERLAP = false; + PhysicsManager.prototype.updateMotion = /* + public update() { + + this._length = this._objects.length; + + for (var i = 0; i < this._length; i++) + { + if (this._objects[i]) + { + this._objects[i].preUpdate(); + this.updateMotion(this._objects[i]); + this.collideWorld(this._objects[i]); + + for (var x = 0; x < this._length; x++) + { + if (this._objects[x] && this._objects[x] !== this._objects[i]) + { + //this.collideShapes(this._objects[i], this._objects[x]); + var r = this.NEWseparate(this._objects[i], this._objects[x]); + //console.log('sep', r); + } + } + + } + } + + } + + public render() { + + // iterate through the objects here, updating and colliding + for (var i = 0; i < this._length; i++) + { + if (this._objects[i]) + { + this._objects[i].render(this.game.stage.context); + } + } + + } + */ + function (body) { + if(body.type == Phaser.Types.BODY_DISABLED) { + return; + } + this._velocityDelta = (this.computeVelocity(body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity) / 2; + body.angularVelocity += this._velocityDelta; + body.angle += body.angularVelocity * this.game.time.elapsed; + body.angularVelocity += this._velocityDelta; + this._velocityDelta = (this.computeVelocity(body.velocity.x, body.gravity.x, body.acceleration.x, body.drag.x) - body.velocity.x) / 2; + body.velocity.x += this._velocityDelta; + this._delta = body.velocity.x * this.game.time.elapsed; + body.velocity.x += this._velocityDelta; + body.position.x += this._delta; + this._velocityDelta = (this.computeVelocity(body.velocity.y, body.gravity.y, body.acceleration.y, body.drag.y) - body.velocity.y) / 2; + body.velocity.y += this._velocityDelta; + this._delta = body.velocity.y * this.game.time.elapsed; + body.velocity.y += this._velocityDelta; + body.position.y += this._delta; + }; + PhysicsManager.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. + */ + function (velocity, gravity, acceleration, drag, max) { + if (typeof gravity === "undefined") { gravity = 0; } + if (typeof acceleration === "undefined") { acceleration = 0; } + if (typeof drag === "undefined") { drag = 0; } + if (typeof max === "undefined") { max = 10000; } + if(acceleration !== 0) { + velocity += (acceleration + gravity) * this.game.time.elapsed; + } else if(drag !== 0) { + this._drag = drag * this.game.time.elapsed; + if(velocity - this._drag > 0) { + velocity = velocity - this._drag; + } else if(velocity + this._drag < 0) { + velocity += this._drag; + } else { + velocity = 0; + } + velocity += gravity; + } + if((velocity != 0) && (max != 10000)) { + if(velocity > max) { + velocity = max; + } else if(velocity < -max) { + velocity = -max; + } + } + return velocity; + }; + PhysicsManager.prototype.separate = /** + * The core Collision separation method. + * @param body1 The first Physics.Body to separate + * @param body2 The second Physics.Body to separate + * @returns {boolean} Returns true if the bodies were separated, otherwise false. + */ + function (body1, body2) { + this._separatedX = this.separateBodyX(body1, body2); + this._separatedY = this.separateBodyY(body1, body2); + return this._separatedX || this._separatedY; + }; + PhysicsManager.prototype.checkHullIntersection = function (body1, body2) { + return ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)); + //if ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)) + //{ + // return true; + //} + //else + //{ + // return false; + //} + }; + PhysicsManager.prototype.separateBodyX = /** + * 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 (body1, body2) { + // Can't separate two disabled or static objects + if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { + return false; + } + // First, get the two object deltas + this._overlap = 0; + if(body1.deltaX != body2.deltaX) { + if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { + this._maxOverlap = body1.deltaXAbs + body2.deltaXAbs + PhysicsManager.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(body1.deltaX > body2.deltaX) { + this._overlap = body1.bounds.right - body2.bounds.x; + if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.RIGHT) || !(body2.allowCollisions & Phaser.Types.LEFT)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.RIGHT; + body2.touching |= Phaser.Types.LEFT; + } + } else if(body1.deltaX < body2.deltaX) { + this._overlap = body1.bounds.x - body2.bounds.width - body2.bounds.x; + if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.LEFT) || !(body2.allowCollisions & Phaser.Types.RIGHT)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.LEFT; + body2.touching |= Phaser.Types.RIGHT; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(this._overlap != 0) { + this._obj1Velocity = body1.velocity.x; + this._obj2Velocity = body2.velocity.x; + /** + * Dynamic = gives and receives impacts + * Static = gives but doesn't receive impacts, cannot be moved by physics + * Kinematic = gives impacts, but never receives, can be moved by physics + */ + // 2 dynamic bodies will exchange velocities + if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 0.5; + body1.position.x = body1.position.x - this._overlap; + body2.position.x += this._overlap; + this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); + this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); + this._average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; + this._obj1NewVelocity -= this._average; + this._obj2NewVelocity -= this._average; + body1.velocity.x = this._average + this._obj1NewVelocity * body1.bounce.x; + body2.velocity.x = this._average + this._obj2NewVelocity * body2.bounce.x; + } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { + // Body 2 is Static or Kinematic + this._overlap *= 2; + body1.position.x -= this._overlap; + body1.velocity.x = this._obj2Velocity - this._obj1Velocity * body1.bounce.x; + } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { + // Body 1 is Static or Kinematic + this._overlap *= 2; + body2.position.x += this._overlap; + body2.velocity.x = this._obj1Velocity - this._obj2Velocity * body2.bounce.x; + } + return true; + } else { + return false; + } + }; + PhysicsManager.prototype.separateBodyY = /** + * 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 (body1, body2) { + // Can't separate two immovable objects + if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { + return false; + } + // First, get the two object deltas + this._overlap = 0; + if(body1.deltaY != body2.deltaY) { + if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { + // This is the only place to use the DeltaAbs values + this._maxOverlap = body1.deltaYAbs + body2.deltaYAbs + PhysicsManager.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(body1.deltaY > body2.deltaY) { + this._overlap = body1.bounds.bottom - body2.bounds.y; + if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.DOWN) || !(body2.allowCollisions & Phaser.Types.UP)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.DOWN; + body2.touching |= Phaser.Types.UP; + } + } else if(body1.deltaY < body2.deltaY) { + this._overlap = body1.bounds.y - body2.bounds.height - body2.bounds.y; + if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.UP) || !(body2.allowCollisions & Phaser.Types.DOWN)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.UP; + body2.touching |= Phaser.Types.DOWN; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(this._overlap != 0) { + this._obj1Velocity = body1.velocity.y; + this._obj2Velocity = body2.velocity.y; + /** + * Dynamic = gives and receives impacts + * Static = gives but doesn't receive impacts, cannot be moved by physics + * Kinematic = gives impacts, but never receives, can be moved by physics + */ + if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 0.5; + body1.position.y = body1.position.y - this._overlap; + body2.position.y += this._overlap; + this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); + this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); + var average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; + this._obj1NewVelocity -= average; + this._obj2NewVelocity -= average; + body1.velocity.y = average + this._obj1NewVelocity * body1.bounce.y; + body2.velocity.y = average + this._obj2NewVelocity * body2.bounce.y; + } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 2; + body1.position.y -= this._overlap; + body1.velocity.y = this._obj2Velocity - this._obj1Velocity * body1.bounce.y; + // This is special case code that handles things like horizontal moving platforms you can ride + //if (body2.parent.active && body2.moves && (body1.deltaY > body2.deltaY)) + if(body2.parent.active && (body1.deltaY > body2.deltaY)) { + body1.position.x += body2.position.x - body2.oldPosition.x; + } + } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 2; + body2.position.y += this._overlap; + body2.velocity.y = this._obj1Velocity - this._obj2Velocity * body2.bounce.y; + // This is special case code that handles things like horizontal moving platforms you can ride + //if (object1.active && body1.moves && (body1.deltaY < body2.deltaY)) + if(body1.parent.active && (body1.deltaY < body2.deltaY)) { + body2.position.x += body1.position.x - body1.oldPosition.x; + } + } + return true; + } else { + return false; + } + }; + PhysicsManager.prototype.overlap = /* + private TILEseparate(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('1 The left side of ShapeA hit the right side of ShapeB', Math.floor(distance.x)); + shapeA.physics.touching |= Phaser.Types.LEFT; + shapeB.physics.touching |= Phaser.Types.RIGHT; + } + else if (tangent.x == -1) + { + console.log('2 The right side of ShapeA hit the left side of ShapeB', Math.floor(distance.x)); + shapeA.physics.touching |= Phaser.Types.RIGHT; + shapeB.physics.touching |= Phaser.Types.LEFT; + } + + if (tangent.y == 1) + { + console.log('3 The top of ShapeA hit the bottom of ShapeB', Math.floor(distance.y)); + shapeA.physics.touching |= Phaser.Types.UP; + shapeB.physics.touching |= Phaser.Types.DOWN; + } + else if (tangent.y == -1) + { + console.log('4 The bottom of ShapeA hit the top of ShapeB', Math.floor(distance.y)); + shapeA.physics.touching |= Phaser.Types.DOWN; + shapeB.physics.touching |= Phaser.Types.UP; + } + + + // only apply collision response forces if the object is travelling into, and not out of, the collision + var dot = Vec2Utils.dot(shapeA.physics.velocity, tangent); + + if (dot < 0) + { + console.log('in to', dot); + + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + else + { + console.log('out of', dot); + } + + shapeA.position.x += Math.floor(distance.x); + //shapeA.bounds.x += Math.floor(distance.x); + + shapeA.position.y += Math.floor(distance.y); + //shapeA.bounds.y += distance.y; + + console.log('------------------------------------------------'); + + } + + private collideWorld(shape:IPhysicsShape) { + + // Collide on the x-axis + this._distance.x = shape.world.bounds.x - (shape.position.x - shape.bounds.halfWidth); + + if (0 < this._distance.x) + { + // Hit Left + this._tangent.setTo(1, 0); + this.separateXWall(shape, this._distance, this._tangent); + } + else + { + this._distance.x = (shape.position.x + shape.bounds.halfWidth) - shape.world.bounds.right; + + if (0 < this._distance.x) + { + // Hit Right + this._tangent.setTo(-1, 0); + this._distance.reverse(); + this.separateXWall(shape, this._distance, this._tangent); + } + } + + // Collide on the y-axis + this._distance.y = shape.world.bounds.y - (shape.position.y - shape.bounds.halfHeight); + + if (0 < this._distance.y) + { + // Hit Top + this._tangent.setTo(0, 1); + this.separateYWall(shape, this._distance, this._tangent); + } + else + { + this._distance.y = (shape.position.y + shape.bounds.halfHeight) - shape.world.bounds.bottom; + + if (0 < this._distance.y) + { + // Hit Bottom + this._tangent.setTo(0, -1); + this._distance.reverse(); + this.separateYWall(shape, this._distance, this._tangent); + } + } + + } + + private separateX(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.LEFT; + shapeB.physics.touching |= Phaser.Types.RIGHT; + } + else + { + console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.RIGHT; + shapeB.physics.touching |= Phaser.Types.LEFT; + } + + // collision edges + //shapeA.oH = tangent.x; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + } + + shapeA.position.x += distance.x; + shapeA.bounds.x += distance.x; + + } + + private separateY(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.y == 1) + { + console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.UP; + shapeB.physics.touching |= Phaser.Types.DOWN; + } + else + { + console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.DOWN; + shapeB.physics.touching |= Phaser.Types.UP; + } + + // collision edges + //shapeA.oV = tangent.y; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + + shapeA.position.y += distance.y; + shapeA.bounds.y += distance.y; + + } + + private separateXWall(shapeA: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.LEFT; + } + else + { + console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.RIGHT; + } + + // collision edges + //shapeA.oH = tangent.x; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + } + + shapeA.position.x += distance.x; + + } + + private separateYWall(shapeA: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.y == 1) + { + console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.UP; + } + else + { + console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.DOWN; + } + + // collision edges + //shapeA.oV = tangent.y; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + + shapeA.position.y += distance.y; + + } + */ + /** + * Checks for overlaps between two objects using the world QuadTree. Can be Sprite vs. Sprite, Sprite 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 Sprite or Group to check. If null the world.group is used. + * @param object2 The second Sprite 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.worldDivisions; + this._quadTree = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.width, this.bounds.height); + this._quadTree.load(object1, object2, notifyCallback, processCallback, context); + this._quadTreeResult = this._quadTree.execute(); + this._quadTree.destroy(); + this._quadTree = null; + return this._quadTreeResult; + }; + PhysicsManager.prototype.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 (object, x, y, width, height, mass, collideLeft, collideRight, collideUp, collideDown, separateX, separateY) { + //var separatedX: bool = this.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); + //var separatedY: bool = this.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); + //return separatedX || separatedY; + return false; + }; + return PhysicsManager; + })(); + Physics.PhysicsManager = PhysicsManager; + /** + * 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. + */ + /* + public separateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + var objDelta: number = object.x - object.last.x; + //var objDelta: number = object.collisionMask.deltaX; + + if (objDelta != 0) + { + // Check if the X hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //var objDeltaAbs: number = object.collisionMask.deltaXAbs; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.x + object.width - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (objDelta < 0) + { + overlap = object.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + //console.log(' + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + /** + * 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. + */ + /* + public separateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 0; + var objDelta: number = object.y - object.last.y; + + if (objDelta != 0) + { + // Check if the Y hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.y + object.height - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (objDelta < 0) + { + overlap = object.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + /** + * 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. + */ + /* + public static NEWseparateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + + if (object.collisionMask.deltaX != 0) + { + // Check if the X hulls actually overlap + //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //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)) + { + var maxOverlap: number = object.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaX > 0) + { + //overlap = object.x + object.width - x; + overlap = object.collisionMask.right - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (object.collisionMask.deltaX < 0) + { + //overlap = object.x - width - x; + overlap = object.collisionMask.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + /** + * 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. + */ + /* + public NEWseparateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 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: 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)) + { + //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + var maxOverlap: number = object.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaY > 0) + { + //overlap = object.y + object.height - y; + overlap = object.collisionMask.bottom - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (object.collisionMask.deltaY < 0) + { + //overlap = object.y - height - y; + overlap = object.collisionMask.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + })(Phaser.Physics || (Phaser.Physics = {})); + var Physics = Phaser.Physics; +})(Phaser || (Phaser = {})); /// /// /// @@ -8928,13 +11540,12 @@ var Phaser; this.group = new Phaser.Group(this._game, 0); this.bounds = new Phaser.Rectangle(0, 0, width, height); this.physics = new Phaser.Physics.PhysicsManager(this._game, width, height); - this.worldDivisions = 6; } World.prototype.update = /** * This is called automatically every frame, and is where main logic happens. */ function () { - this.physics.update(); + //this.physics.update(); this.group.update(); this.cameras.update(); }; @@ -9026,6 +11637,282 @@ var Phaser; })(); Phaser.World = World; })(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.game = game; + } + Motion.prototype.velocityFromAngle = /** + * Given the angle and speed calculate the velocity and return it as a Point + * + * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + function (angle, speed) { + if(isNaN(speed)) { + speed = 0; + } + var a = this.game.math.degreesToRadians(angle); + return new Phaser.Point((Math.cos(a) * speed), (Math.sin(a) * speed)); + }; + Motion.prototype.moveTowardsObject = /** + * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * If you need the object to accelerate, see accelerateTowardsObject() instead + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) + * + * @param {Sprite} source The Sprite on which the velocity will be set + * @param {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsObject = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsObject() instead. + * + * @param {Sprite} source The Sprite on which the acceleration will be set + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.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 {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsMouse = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsMouse() instead. + * + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.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 {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsPoint = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsPoint() instead. + * + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.maxVelocity.y = ySpeedMax; + }; + Motion.prototype.distanceBetween = /** + * Find the distance between two Sprites, taking their origin into account + * + * @param {Sprite} a The first Sprite + * @param {Sprite} b The second Sprite + * @return {number} int Distance (in pixels) + */ + function (a, b) { + return Phaser.Vec2Utils.distance(a.body.position, b.body.position); + }; + Motion.prototype.distanceToPoint = /** + * Find the distance from an Sprite to the given Point, taking the source origin into account + * + * @param {Sprite} 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 {Sprite} 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 {Sprite} a The Sprite to test from + * @param {Point} target The Point to angle the Sprite towards + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + function (a, target, asDegrees) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + var dx = (target.x) - (a.x + a.origin.x); + var dy = (target.y) - (a.y + a.origin.y); + if(asDegrees) { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + 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 {Sprite} a The Sprite to test from + * @param {Sprite} 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(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + Motion.prototype.velocityFromFacing = /** + * Given the Sprite and speed calculate the velocity and return it as an Point based on the direction the sprite is facing + * + * @param {Sprite} 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.body.facing == Phaser.Types.LEFT) { + a = this.game.math.degreesToRadians(180); + } else if(parent.body.facing == Phaser.Types.RIGHT) { + a = this.game.math.degreesToRadians(0); + } else if(parent.body.facing == Phaser.Types.UP) { + a = this.game.math.degreesToRadians(-90); + } else if(parent.body.facing == Phaser.Types.DOWN) { + a = this.game.math.degreesToRadians(90); + } + return new Phaser.Point(Math.cos(a) * speed, 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 {Sprite} 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 = Phaser.SpriteUtils.getScreenXY(a); + var dx = a.game.input.x - p.x; + var dy = a.game.input.y - p.y; + if(asDegrees) { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + return Motion; + })(); + Phaser.Motion = Motion; +})(Phaser || (Phaser = {})); /// /** * Phaser - Device @@ -11388,271 +14275,6 @@ var Phaser; Phaser.HeadlessRenderer = HeadlessRenderer; })(Phaser || (Phaser = {})); /// -/// -/// -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ -var Phaser; -(function (Phaser) { - var ScrollRegion = (function () { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. - * - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @param speedX {number} X-axis scrolling speed. - * @param speedY {number} Y-axis scrolling speed. - */ - function ScrollRegion(x, y, width, height, speedX, speedY) { - this._anchorWidth = 0; - this._anchorHeight = 0; - this._inverseWidth = 0; - this._inverseHeight = 0; - /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - this.visible = true; - // Our seamless scrolling quads - this._A = new Phaser.Rectangle(x, y, width, height); - this._B = new Phaser.Rectangle(x, y, width, height); - this._C = new Phaser.Rectangle(x, y, width, height); - this._D = new Phaser.Rectangle(x, y, width, height); - this._scroll = new Phaser.Vec2(); - this._bounds = new Phaser.Rectangle(x, y, width, height); - this.scrollSpeed = new Phaser.Vec2(speedX, speedY); - } - ScrollRegion.prototype.update = /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - function (delta) { - this._scroll.x += this.scrollSpeed.x; - this._scroll.y += this.scrollSpeed.y; - if(this._scroll.x > this._bounds.right) { - this._scroll.x = this._bounds.x; - } - if(this._scroll.x < this._bounds.x) { - this._scroll.x = this._bounds.right; - } - if(this._scroll.y > this._bounds.bottom) { - this._scroll.y = this._bounds.y; - } - if(this._scroll.y < this._bounds.y) { - this._scroll.y = this._bounds.bottom; - } - // Anchor Dimensions - this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; - this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; - if(this._anchorWidth > this._bounds.width) { - this._anchorWidth = this._bounds.width; - } - if(this._anchorHeight > this._bounds.height) { - this._anchorHeight = this._bounds.height; - } - this._inverseWidth = this._bounds.width - this._anchorWidth; - this._inverseHeight = this._bounds.height - this._anchorHeight; - // Rectangle A - this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); - // Rectangle B - this._B.y = this._scroll.y; - this._B.width = this._inverseWidth; - this._B.height = this._anchorHeight; - // Rectangle C - this._C.x = this._scroll.x; - this._C.width = this._anchorWidth; - this._C.height = this._inverseHeight; - // Rectangle D - this._D.width = this._inverseWidth; - this._D.height = this._inverseHeight; - }; - ScrollRegion.prototype.render = /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - function (context, texture, dx, dy, dw, dh) { - if(this.visible == false) { - return; - } - // dx/dy are the world coordinates to render the FULL ScrollZone into. - // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. - this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); - this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); - this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); - this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); - //context.fillStyle = 'rgb(255,255,255)'; - //context.font = '18px Arial'; - //context.fillText('RectangleA: ' + this._A.toString(), 32, 450); - //context.fillText('RectangleB: ' + this._B.toString(), 32, 480); - //context.fillText('RectangleC: ' + this._C.toString(), 32, 510); - //context.fillText('RectangleD: ' + this._D.toString(), 32, 540); - }; - ScrollRegion.prototype.crop = /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { - offsetX += destX; - offsetY += destY; - if(srcW > (destX + destW) - offsetX) { - srcW = (destX + destW) - offsetX; - } - if(srcH > (destY + destH) - offsetY) { - srcH = (destY + destH) - offsetY; - } - srcX = Math.floor(srcX); - srcY = Math.floor(srcY); - srcW = Math.floor(srcW); - srcH = Math.floor(srcH); - offsetX = Math.floor(offsetX + this._bounds.x); - offsetY = Math.floor(offsetY + this._bounds.y); - if(srcW > 0 && srcH > 0) { - context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); - } - }; - return ScrollRegion; - })(); - Phaser.ScrollRegion = ScrollRegion; -})(Phaser || (Phaser = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -/// -/// -/// -/** -* 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, key, width, height); - this.type = Phaser.Types.SCROLLZONE; - this.render = game.renderer.renderScrollZone; - this.physics.moves = false; - this.regions = []; - if(this.texture.loaded) { - if(width > this.width || height > this.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.width || height < this.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.createRepeatingTexture = /** - * Create repeating texture with _texture, and store it into the _dynamicTexture. - * Used to create texture when texture image is small than size of the zone. - */ - function (regionWidth, regionHeight) { - // Work out how many we'll need of the source image to make it tile properly - var tileWidth = Math.ceil(this.width / regionWidth) * regionWidth; - var tileHeight = Math.ceil(this.height / regionHeight) * regionHeight; - var dt = new Phaser.DynamicTexture(this.game, tileWidth, tileHeight); - dt.context.rect(0, 0, tileWidth, tileHeight); - dt.context.fillStyle = dt.context.createPattern(this.texture.imageTexture, "repeat"); - dt.context.fill(); - this.texture.loadDynamicTexture(dt); - }; - return ScrollZone; - })(Phaser.Sprite); - Phaser.ScrollZone = ScrollZone; -})(Phaser || (Phaser = {})); -/// /// /// /// @@ -11687,8 +14309,6 @@ var Phaser; this._game.world.group.render(this, this._camera); this._camera.postRender(); } - // Physics Debug layer - this._game.world.physics.render(); }; CanvasRenderer.prototype.renderSprite = /** * Render this sprite to specific camera. Called by game loop after update(). @@ -11737,9 +14357,9 @@ var Phaser; } // Rotation and Flipped if(sprite.modified) { - if(sprite.texture.renderRotation == true && (sprite.rotation !== 0 || sprite.rotationOffset !== 0)) { - this._sin = Math.sin(sprite.game.math.degreesToRadians(sprite.rotationOffset + sprite.rotation)); - this._cos = Math.cos(sprite.game.math.degreesToRadians(sprite.rotationOffset + sprite.rotation)); + if(sprite.texture.renderRotation == true && (sprite.angle !== 0 || sprite.angleOffset !== 0)) { + this._sin = Math.sin(sprite.game.math.degreesToRadians(sprite.angleOffset + sprite.angle)); + this._cos = Math.cos(sprite.game.math.degreesToRadians(sprite.angleOffset + sprite.angle)); } // setTransform(a, b, c, d, e, f); // a = scale x @@ -11785,11 +14405,6 @@ var Phaser; if(sprite.modified) { sprite.texture.context.restore(); } - //if (this.renderDebug) - //{ - // this.renderBounds(camera, cameraOffsetX, cameraOffsetY); - //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); - //} if(this._ga > -1) { sprite.texture.context.globalAlpha = this._ga; } @@ -11829,9 +14444,9 @@ var Phaser; } // Rotation and Flipped if(scrollZone.modified) { - if(scrollZone.texture.renderRotation == true && (scrollZone.rotation !== 0 || scrollZone.rotationOffset !== 0)) { - this._sin = Math.sin(scrollZone.game.math.degreesToRadians(scrollZone.rotationOffset + scrollZone.rotation)); - this._cos = Math.cos(scrollZone.game.math.degreesToRadians(scrollZone.rotationOffset + scrollZone.rotation)); + if(scrollZone.texture.renderRotation == true && (scrollZone.angle !== 0 || scrollZone.angleOffset !== 0)) { + this._sin = Math.sin(scrollZone.game.math.degreesToRadians(scrollZone.angleOffset + scrollZone.angle)); + this._cos = Math.cos(scrollZone.game.math.degreesToRadians(scrollZone.angleOffset + scrollZone.angle)); } // setTransform(a, b, c, d, e, f); // a = scale x @@ -11868,11 +14483,6 @@ var Phaser; if(scrollZone.modified) { scrollZone.texture.context.restore(); } - //if (this.renderDebug) - //{ - // this.renderBounds(camera, cameraOffsetX, cameraOffsetY); - //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); - //} if(this._ga > -1) { scrollZone.texture.context.globalAlpha = this._ga; } @@ -11882,20 +14492,27 @@ var Phaser; })(); Phaser.CanvasRenderer = CanvasRenderer; })(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// /// /// /// /// -/// -/// -/// /// /// /// /// /// +/// /// /// /// @@ -12050,14 +14667,13 @@ var Phaser; }, 13); } else { this.device = new Phaser.Device(); - //this.motion = new Motion(this); + 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 Collision(this); this.loader = new Phaser.Loader(this, this.loadComplete); this.time = new Phaser.Time(this); this.tweens = new Phaser.TweenManager(this); @@ -12304,21 +14920,25 @@ var Phaser; enumerable: true, configurable: true }); + Game.prototype.collide = /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, context) { + if (typeof objectOrGroup1 === "undefined") { objectOrGroup1 = null; } + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof context === "undefined") { context = this.callbackContext; } + return this.world.physics.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, this.world.physics.separate, context); + }; 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 () { + get: function () { return this.world.cameras.current; }, enumerable: true, @@ -12328,468 +14948,117 @@ var Phaser; })(); Phaser.Game = Game; })(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.multiplyByScalar = /** - * Multiply 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.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.equals = /** - * Check if both the x and y of this vector equal the given value. - * - * @return {Boolean} - */ - function (value) { - return (this.x == value && this.y == value); - }; - 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 = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// + /// + /// + /// /** - * Phaser - Physics - Circle - */ - (function (Physics) { - var Circle = (function () { - function Circle(game, sprite, x, y, diameter) { - this.game = game; - this.world = game.world.physics; - if(sprite !== null) { - this.sprite = sprite; - this.scale = Phaser.Vec2Utils.clone(this.sprite.scale); - } else { - this.sprite = null; - this.physics = null; - this.scale = new Phaser.Vec2(1, 1); - } - this.diameter = diameter; - this.radius = diameter / 2; - this.bounds = new Phaser.Rectangle(x + Math.round(diameter / 2), y + Math.round(diameter / 2), diameter, diameter); - this.position = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Phaser.Vec2(0, 0); - } - Circle.prototype.preUpdate = function () { - this.oldPosition.copyFrom(this.position); - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - if(this.sprite) { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - // Update scale / dimensions - if(Phaser.Vec2Utils.equals(this.scale, this.sprite.scale) == false) { - this.scale.copyFrom(this.sprite.scale); - // needs to be radius based (+ square) - //this.bounds.width = this.sprite.width; - //this.bounds.height = this.sprite.height; - } - } - }; - Circle.prototype.update = function () { - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - }; - Circle.prototype.setSize = function (width, height) { - this.bounds.width = width; - this.bounds.height = height; - }; - Circle.prototype.render = function (context) { - // center point - context.fillStyle = 'rgba(255,0,0,0.5)'; - context.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2); - context.rect(this.position.x, this.position.y, 2, 2); - context.fill(); - /* - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - */ - }; - Object.defineProperty(Circle.prototype, "hullWidth", { - get: function () { - if(this.deltaX > 0) { - //return this.bounds.width + this.deltaX; - return this.diameter + this.deltaX; - } else { - //return this.bounds.width - this.deltaX; - return this.diameter - this.deltaX; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullHeight", { - get: function () { - if(this.deltaY > 0) { - //return this.bounds.height + this.deltaY; - return this.diameter + this.deltaY; - } else { - //return this.bounds.height - this.deltaY; - return this.diameter - this.deltaY; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullX", { - get: function () { - if(this.position.x < this.oldPosition.x) { - return this.position.x; - } else { - return this.oldPosition.x; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullY", { - get: function () { - if(this.position.y < this.oldPosition.y) { - return this.position.y; - } else { - return this.oldPosition.y; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaXAbs", { - get: function () { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaYAbs", { - get: function () { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaX", { - get: function () { - return this.position.x - this.oldPosition.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaY", { - get: function () { - return this.position.y - this.oldPosition.y; - }, - enumerable: true, - configurable: true - }); - return Circle; - })(); - Physics.Circle = Circle; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /// - /** - * Phaser - Components - Physics + * Phaser - Components - Events + * + * */ (function (Components) { - var Physics = (function () { - function Physics(parent) { - /** - * Whether this object will be moved by impacts with other objects or not. - * @type {boolean} - */ - this.immovable = false; - /** - * Set this to false if you want to skip the automatic movement stuff - * @type {boolean} - */ - this.moves = true; - this.mass = 1; - this.game = parent.game; + var Events = (function () { + function Events(parent, key) { + if (typeof key === "undefined") { key = ''; } + this._game = parent.game; this._sprite = parent; - this.gravity = Phaser.Vec2Utils.clone(this.game.world.physics.gravity); - this.drag = Phaser.Vec2Utils.clone(this.game.world.physics.drag); - this.bounce = Phaser.Vec2Utils.clone(this.game.world.physics.bounce); - this.friction = Phaser.Vec2Utils.clone(this.game.world.physics.friction); - this.velocity = new Phaser.Vec2(); - this.acceleration = new Phaser.Vec2(); - this.touching = Phaser.Types.NONE; - this.wasTouching = Phaser.Types.NONE; - this.allowCollisions = Phaser.Types.ANY; - this.shape = this.game.world.physics.add(new Phaser.Physics.AABB(this.game, this._sprite, this._sprite.x, this._sprite.y, this._sprite.width, this._sprite.height)); } - Physics.prototype.setCircle = function (diameter) { - this.game.world.physics.remove(this.shape); - this.shape = this.game.world.physics.add(new Phaser.Physics.Circle(this.game, this._sprite, this._sprite.x, this._sprite.y, diameter)); - this._sprite.physics.shape.physics = this; - }; - Physics.prototype.update = /** - * Internal function for updating the position and speed of this object. - */ - function () { - if(this.moves && this.shape) { - this._sprite.x = (this.shape.position.x - this.shape.bounds.halfWidth) - this.shape.offset.x; - this._sprite.y = (this.shape.position.y - this.shape.bounds.halfHeight) - this.shape.offset.y; - } - }; - Physics.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._sprite.texture.context.fillStyle = color; - this._sprite.texture.context.fillText('Sprite: (' + this._sprite.frameBounds.width + ' x ' + this._sprite.frameBounds.height + ')', x, y); - //this._sprite.texture.context.fillText('x: ' + this._sprite.frameBounds.x.toFixed(1) + ' y: ' + this._sprite.frameBounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('x: ' + this.shape.bounds.x.toFixed(1) + ' y: ' + this.shape.bounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); - this._sprite.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); - }; - return Physics; + return Events; })(); - Components.Physics = Physics; + Components.Events = Events; })(Phaser.Components || (Phaser.Components = {})); var Components = Phaser.Components; })(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /** + * Phaser - Components - Debug + * + * + */ + (function (Components) { + var Debug = (function () { + function Debug() { + /** + * 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)'; + } + return Debug; + })(); + Components.Debug = Debug; + /** + * 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); + + } + */ + })(Phaser.Components || (Phaser.Components = {})); + var Components = Phaser.Components; +})(Phaser || (Phaser = {})); /// /** * Phaser - Polygon @@ -12826,503 +15095,6 @@ var Phaser; 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)); - return true; - }; - CircleUtils.containsPoint = /** - * Return true if the coordinates of the given Point object are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method containsPoint - * @param {Circle} a - The Circle object. - * @param {Point} The Point object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function containsPoint(a, point) { - return CircleUtils.contains(a, point.x, point.y); - }; - CircleUtils.containsCircle = /** - * Return true if the given Circle is contained entirely within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. - * @method containsCircle - * @param {Circle} The Circle object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function containsCircle(a, b) { - //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); - return true; - }; - CircleUtils.distanceBetween = /** - * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) - * @method distanceBetween - * @param {Circle} a - The Circle object. - * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. - * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - function distanceBetween(a, target, round) { - if (typeof round === "undefined") { round = false; } - var dx = a.x - target.x; - var dy = a.y - target.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - CircleUtils.equals = /** - * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. - * @method equals - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. - **/ - function equals(a, b) { - return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); - }; - CircleUtils.intersects = /** - * Determines whether the two Circle objects intersect. - * This method checks the radius distances between the two Circle objects to see if they intersect. - * @method intersects - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. - **/ - function intersects(a, b) { - return (CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); - }; - CircleUtils.circumferencePoint = /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method circumferencePoint - * @param {Circle} a - The first Circle object. - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - **/ - function circumferencePoint(a, angle, asDegrees, out) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof out === "undefined") { out = new Phaser.Point(); } - if(asDegrees === true) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; - } - return out.setTo(a.x + a.radius * Math.cos(angle), a.y + a.radius * Math.sin(angle)); - }; - return CircleUtils; - })(); - Phaser.CircleUtils = CircleUtils; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - LinkedList -* -* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! -*/ -var Phaser; -(function (Phaser) { - var LinkedList = (function () { - /** - * Creates a new link, and sets object and next to null. - */ - function LinkedList() { - this.object = null; - this.next = null; - } - LinkedList.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.object = null; - if(this.next != null) { - this.next.destroy(); - } - this.next = null; - }; - return LinkedList; - })(); - Phaser.LinkedList = LinkedList; -})(Phaser || (Phaser = {})); -/// -/// -/// -/** -* Phaser - QuadTree -* -* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. -* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, -* or the A list against the B list. Handy for different things! -*/ -var Phaser; -(function (Phaser) { - var QuadTree = (function (_super) { - __extends(QuadTree, _super); - /** - * Instantiate a new Quad Tree node. - * - * @param {Number} x The X-coordinate of the point in space. - * @param {Number} y The Y-coordinate of the point in space. - * @param {Number} width Desired width of this node. - * @param {Number} height Desired height of this node. - * @param {Number} parent The parent branch or node. Pass null to create a root. - */ - function QuadTree(x, y, width, height, parent) { - if (typeof parent === "undefined") { parent = null; } - _super.call(this, x, y, width, height); - this._headA = this._tailA = new Phaser.LinkedList(); - this._headB = this._tailB = new Phaser.LinkedList(); - //Copy the parent's children (if there are any) - if(parent != null) { - if(parent._headA.object != null) { - this._iterator = parent._headA; - while(this._iterator != null) { - if(this._tailA.object != null) { - this._ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - this._ot.next = this._tailA; - } - this._tailA.object = this._iterator.object; - this._iterator = this._iterator.next; - } - } - if(parent._headB.object != null) { - this._iterator = parent._headB; - while(this._iterator != null) { - if(this._tailB.object != null) { - this._ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - this._ot.next = this._tailB; - } - this._tailB.object = this._iterator.object; - this._iterator = this._iterator.next; - } - } - } else { - QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); - } - this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); - //Set up comparison/sort helpers - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - this._leftEdge = this.x; - this._rightEdge = this.x + this.width; - this._halfWidth = this.width / 2; - this._midpointX = this._leftEdge + this._halfWidth; - this._topEdge = this.y; - this._bottomEdge = this.y + this.height; - this._halfHeight = this.height / 2; - this._midpointY = this._topEdge + this._halfHeight; - } - QuadTree.A_LIST = 0; - QuadTree.B_LIST = 1; - QuadTree.prototype.destroy = /** - * Clean up memory. - */ - function () { - this._tailA.destroy(); - this._tailB.destroy(); - this._headA.destroy(); - this._headB.destroy(); - this._tailA = null; - this._tailB = null; - this._headA = null; - this._headB = null; - if(this._northWestTree != null) { - this._northWestTree.destroy(); - } - if(this._northEastTree != null) { - this._northEastTree.destroy(); - } - if(this._southEastTree != null) { - this._southEastTree.destroy(); - } - if(this._southWestTree != null) { - this._southWestTree.destroy(); - } - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - QuadTree._object = null; - QuadTree._processingCallback = null; - QuadTree._notifyCallback = null; - }; - QuadTree.prototype.load = /** - * Load objects and/or groups into the quad tree, and register notify and processing callbacks. - * - * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. - * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. - * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. - * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). - * @param context The context in which the callbacks will be called - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof processCallback === "undefined") { processCallback = null; } - if (typeof context === "undefined") { context = null; } - this.add(objectOrGroup1, QuadTree.A_LIST); - if(objectOrGroup2 != null) { - this.add(objectOrGroup2, QuadTree.B_LIST); - QuadTree._useBothLists = true; - } else { - QuadTree._useBothLists = false; - } - QuadTree._notifyCallback = notifyCallback; - QuadTree._processingCallback = processCallback; - QuadTree._callbackContext = context; - }; - QuadTree.prototype.add = /** - * Call this function to add an object to the root of the tree. - * This function will recursively add all group members, but - * not the groups themselves. - * - * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. - * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. - */ - function (objectOrGroup, list) { - QuadTree._list = list; - if(objectOrGroup.isGroup == true) { - this._i = 0; - this._members = objectOrGroup['members']; - this._l = objectOrGroup['length']; - while(this._i < this._l) { - this._basic = this._members[this._i++]; - if(this._basic != null && this._basic.exists) { - if(this._basic.type == Phaser.Types.GROUP) { - this.add(this._basic, list); - } else { - QuadTree._object = this._basic; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - } - } - } else { - QuadTree._object = objectOrGroup; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - }; - QuadTree.prototype.addObject = /** - * Internal function for recursively navigating and creating the tree - * while adding objects to the appropriate nodes. - */ - function () { - //If this quad (not its children) lies entirely inside this object, add it here - if(!this._canSubdivide || ((this._leftEdge >= QuadTree._object.collisionMask.x) && (this._rightEdge <= QuadTree._object.collisionMask.right) && (this._topEdge >= QuadTree._object.collisionMask.y) && (this._bottomEdge <= QuadTree._object.collisionMask.bottom))) { - this.addToList(); - return; - } - //See if the selected object fits completely inside any of the quadrants - if((QuadTree._object.collisionMask.x > this._leftEdge) && (QuadTree._object.collisionMask.right < this._midpointX)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - return; - } - } - if((QuadTree._object.collisionMask.x > this._midpointX) && (QuadTree._object.collisionMask.right < this._rightEdge)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - return; - } - } - //If it wasn't completely contained we have to check out the partial overlaps - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - } - }; - QuadTree.prototype.addToList = /** - * Internal function for recursively adding objects to leaf lists. - */ - function () { - if(QuadTree._list == QuadTree.A_LIST) { - if(this._tailA.object != null) { - this._ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - this._ot.next = this._tailA; - } - this._tailA.object = QuadTree._object; - } else { - if(this._tailB.object != null) { - this._ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - this._ot.next = this._tailB; - } - this._tailB.object = QuadTree._object; - } - if(!this._canSubdivide) { - return; - } - if(this._northWestTree != null) { - this._northWestTree.addToList(); - } - if(this._northEastTree != null) { - this._northEastTree.addToList(); - } - if(this._southEastTree != null) { - this._southEastTree.addToList(); - } - if(this._southWestTree != null) { - this._southWestTree.addToList(); - } - }; - QuadTree.prototype.execute = /** - * QuadTree's other main function. Call this after adding objects - * using QuadTree.load() to compare the objects that you loaded. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - this._overlapProcessed = false; - if(this._headA.object != null) { - this._iterator = this._headA; - while(this._iterator != null) { - QuadTree._object = this._iterator.object; - if(QuadTree._useBothLists) { - QuadTree._iterator = this._headB; - } else { - QuadTree._iterator = this._iterator.next; - } - if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { - this._overlapProcessed = true; - } - this._iterator = this._iterator.next; - } - } - //Advance through the tree by calling overlap on each child - if((this._northWestTree != null) && this._northWestTree.execute()) { - this._overlapProcessed = true; - } - if((this._northEastTree != null) && this._northEastTree.execute()) { - this._overlapProcessed = true; - } - if((this._southEastTree != null) && this._southEastTree.execute()) { - this._overlapProcessed = true; - } - if((this._southWestTree != null) && this._southWestTree.execute()) { - this._overlapProcessed = true; - } - return this._overlapProcessed; - }; - QuadTree.prototype.overlapNode = /** - * A private for comparing an object against the contents of a node. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - //Walk the list and check for overlaps - this._overlapProcessed = false; - while(QuadTree._iterator != null) { - if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) { - break; - } - this._checkObject = QuadTree._iterator.object; - if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.allowCollisions <= 0)) { - QuadTree._iterator = QuadTree._iterator.next; - continue; - } - if(QuadTree._object.collisionMask.checkHullIntersection(this._checkObject.collisionMask)) { - //Execute callback functions if they exist - if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { - this._overlapProcessed = true; - } - if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { - if(QuadTree._callbackContext !== null) { - QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); - } else { - QuadTree._notifyCallback(QuadTree._object, this._checkObject); - } - } - } - QuadTree._iterator = QuadTree._iterator.next; - } - return this._overlapProcessed; - }; - return QuadTree; - })(Phaser.Rectangle); - Phaser.QuadTree = QuadTree; -})(Phaser || (Phaser = {})); -/// /** * Phaser - Line * diff --git a/Tests/physics/aabb 1.js b/Tests/physics/aabb 1.js index 1c79427d..91312c9b 100644 --- a/Tests/physics/aabb 1.js +++ b/Tests/physics/aabb 1.js @@ -14,24 +14,24 @@ //atari.physics.shape.setSize(150, 50); //atari.physics.shape.offset.setTo(50, 25); //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(0.7, 0.7); - atari.physics.drag.setTo(10, 10); + atari.body.bounce.setTo(0.7, 0.7); + atari.body.drag.setTo(10, 10); } function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; + atari.body.acceleration.x = 0; + atari.body.acceleration.y = 0; if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; + atari.body.acceleration.x = -150; } else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; + atari.body.acceleration.x = 150; } if(game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; + atari.body.acceleration.y = -150; } else if(game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; + atari.body.acceleration.y = 150; } } function render() { - atari.physics.renderDebugInfo(16, 16); + atari.body.renderDebugInfo(16, 16); } })(); diff --git a/Tests/physics/aabb 1.ts b/Tests/physics/aabb 1.ts index cd906c54..91b9f2f7 100644 --- a/Tests/physics/aabb 1.ts +++ b/Tests/physics/aabb 1.ts @@ -24,39 +24,39 @@ //atari.physics.shape.offset.setTo(50, 25); //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(0.7, 0.7); - atari.physics.drag.setTo(10, 10); + atari.body.bounce.setTo(0.7, 0.7); + atari.body.drag.setTo(10, 10); } function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; + atari.body.acceleration.x = 0; + atari.body.acceleration.y = 0; if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; + atari.body.acceleration.x = -150; } else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; + atari.body.acceleration.x = 150; } if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; + atari.body.acceleration.y = -150; } else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; + atari.body.acceleration.y = 150; } } function render() { - atari.physics.renderDebugInfo(16, 16); + atari.body.renderDebugInfo(16, 16); } diff --git a/Tests/physics/aabb vs aabb 1.js b/Tests/physics/aabb vs aabb 1.js index 0fa3b93a..031a360a 100644 --- a/Tests/physics/aabb vs aabb 1.js +++ b/Tests/physics/aabb vs aabb 1.js @@ -14,34 +14,34 @@ //atari = game.add.sprite(350, 500, 'atari'); atari = game.add.sprite(0, 310, 'atari'); card = game.add.sprite(400, 300, 'card'); - //card.physics.immovable = true; + //card.body.immovable = true; //atari.texture.alpha = 0.5; //atari.scale.setTo(1.5, 1.5); - atari.physics.shape.setSize(150, 50); - atari.physics.shape.offset.setTo(50, 25); - //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(1, 1); - //atari.physics.drag.setTo(10, 10); - card.physics.bounce.setTo(0.7, 0.7); - //card.physics.velocity.x = -50; + //atari.body.shape.setSize(150, 50); + //atari.body.shape.offset.setTo(50, 25); + //atari.body.gravity.setTo(0, 2); + atari.body.bounce.setTo(1, 1); + //atari.body.drag.setTo(10, 10); + card.body.bounce.setTo(0.7, 0.7); + //card.body.velocity.x = -50; } function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; + atari.body.acceleration.x = 0; + atari.body.acceleration.y = 0; if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; + atari.body.acceleration.x = -150; } else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; + atari.body.acceleration.x = 150; } if(game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; + atari.body.acceleration.y = -150; } else if(game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; + atari.body.acceleration.y = 150; } // collide? } function render() { - atari.physics.renderDebugInfo(16, 16); - card.physics.renderDebugInfo(200, 16); + atari.body.renderDebugInfo(16, 16); + card.body.renderDebugInfo(200, 16); } })(); diff --git a/Tests/physics/aabb vs aabb 1.ts b/Tests/physics/aabb vs aabb 1.ts index 9bd68ab0..0bd06e86 100644 --- a/Tests/physics/aabb vs aabb 1.ts +++ b/Tests/physics/aabb vs aabb 1.ts @@ -23,44 +23,44 @@ atari = game.add.sprite(0, 310, 'atari'); card = game.add.sprite(400, 300, 'card'); - //card.physics.immovable = true; + //card.body.immovable = true; //atari.texture.alpha = 0.5; //atari.scale.setTo(1.5, 1.5); - atari.physics.shape.setSize(150, 50); - atari.physics.shape.offset.setTo(50, 25); + //atari.body.shape.setSize(150, 50); + //atari.body.shape.offset.setTo(50, 25); - //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(1, 1); - //atari.physics.drag.setTo(10, 10); + //atari.body.gravity.setTo(0, 2); + atari.body.bounce.setTo(1, 1); + //atari.body.drag.setTo(10, 10); - card.physics.bounce.setTo(0.7, 0.7); - //card.physics.velocity.x = -50; + card.body.bounce.setTo(0.7, 0.7); + //card.body.velocity.x = -50; } function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; + atari.body.acceleration.x = 0; + atari.body.acceleration.y = 0; if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; + atari.body.acceleration.x = -150; } else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; + atari.body.acceleration.x = 150; } if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; + atari.body.acceleration.y = -150; } else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; + atari.body.acceleration.y = 150; } // collide? @@ -69,8 +69,8 @@ function render() { - atari.physics.renderDebugInfo(16, 16); - card.physics.renderDebugInfo(200, 16); + atari.body.renderDebugInfo(16, 16); + card.body.renderDebugInfo(200, 16); } diff --git a/Tests/physics/circle 1.js b/Tests/physics/circle 1.js deleted file mode 100644 index d74bba72..00000000 --- a/Tests/physics/circle 1.js +++ /dev/null @@ -1,42 +0,0 @@ -/// -(function () { - var game = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - // Using Phasers asset loader we load up a PNG from the assets folder - game.loader.addImageFile('atari', 'assets/sprites/mushroom2.png'); - game.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - game.loader.load(); - } - var atari; - var card; - function create() { - atari = game.add.sprite(200, 300, 'atari'); - card = game.add.sprite(400, 300, 'card'); - //atari.texture.alpha = 0.5; - //atari.scale.setTo(1.5, 1.5); - atari.physics.setCircle(100); - //atari.physics.shape.setSize(150, 50); - //atari.physics.shape.offset.setTo(7, 5); - //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(0.7, 0.7); - //atari.physics.drag.setTo(10, 10); - card.physics.bounce.setTo(0.7, 0.7); - } - function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; - if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; - } else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; - } - if(game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; - } else if(game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; - } - } - function render() { - atari.physics.renderDebugInfo(16, 16); - } -})(); diff --git a/Tests/physics/circle 1.ts b/Tests/physics/circle 1.ts deleted file mode 100644 index 6f66e48e..00000000 --- a/Tests/physics/circle 1.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// - -(function () { - - var game = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - // Using Phasers asset loader we load up a PNG from the assets folder - game.loader.addImageFile('atari', 'assets/sprites/mushroom2.png'); - game.loader.addImageFile('card', 'assets/sprites/mana_card.png'); - game.loader.load(); - - } - - var atari: Phaser.Sprite; - var card: Phaser.Sprite; - - function create() { - - atari = game.add.sprite(200, 300, 'atari'); - card = game.add.sprite(400, 300, 'card'); - //atari.texture.alpha = 0.5; - //atari.scale.setTo(1.5, 1.5); - - atari.physics.setCircle(100); - - //atari.physics.shape.setSize(150, 50); - //atari.physics.shape.offset.setTo(7, 5); - - //atari.physics.gravity.setTo(0, 2); - atari.physics.bounce.setTo(0.7, 0.7); - //atari.physics.drag.setTo(10, 10); - - card.physics.bounce.setTo(0.7, 0.7); - - } - - function update() { - - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; - - if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - atari.physics.acceleration.x = -150; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - atari.physics.acceleration.x = 150; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - atari.physics.acceleration.y = -150; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - atari.physics.acceleration.y = 150; - } - - } - - function render() { - - atari.physics.renderDebugInfo(16, 16); - - } - -})(); diff --git a/Tests/physics/test 1.js b/Tests/physics/test 1.js deleted file mode 100644 index 814eabd8..00000000 --- a/Tests/physics/test 1.js +++ /dev/null @@ -1,42 +0,0 @@ -/// -/// -/// -(function () { - var game = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - function init() { - // Using Phasers asset loader we load up a PNG from the assets folder - game.loader.addImageFile('atari', 'assets/sprites/atari800xl.png'); - game.loader.load(); - } - var atari; - var p; - var atari2; - var p2; - function create() { - atari = game.add.sprite(200, 300, 'atari'); - atari.texture.alpha = 0.2; - atari2 = game.add.sprite(500, 300, 'atari'); - atari2.texture.alpha = 0.2; - p = new Phaser.Polygon(game, Phaser.SpriteUtils.getAsPoints(atari)); - p2 = new Phaser.Polygon(game, Phaser.SpriteUtils.getAsPoints(atari2)); - } - function update() { - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; - if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - atari.physics.acceleration.x = -150; - } else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - atari.physics.acceleration.x = 150; - } - if(game.input.keyboard.isDown(Phaser.Keyboard.UP)) { - atari.physics.acceleration.y = -150; - } else if(game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { - atari.physics.acceleration.y = 150; - } - } - function render() { - atari.physics.renderDebugInfo(16, 16); - p.render(); - p2.render(); - } -})(); diff --git a/Tests/physics/test 1.ts b/Tests/physics/test 1.ts deleted file mode 100644 index 19744ede..00000000 --- a/Tests/physics/test 1.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// -/// -/// - -(function () { - - var game = new Phaser.Game(this, 'game', 800, 600, init, create, update, render); - - function init() { - - // Using Phasers asset loader we load up a PNG from the assets folder - game.loader.addImageFile('atari', 'assets/sprites/atari800xl.png'); - game.loader.load(); - - } - - var atari: Phaser.Sprite; - var p: Phaser.Polygon; - - var atari2: Phaser.Sprite; - var p2: Phaser.Polygon; - - function create() { - - atari = game.add.sprite(200, 300, 'atari'); - atari.texture.alpha = 0.2; - - atari2 = game.add.sprite(500, 300, 'atari'); - atari2.texture.alpha = 0.2; - - p = new Phaser.Polygon(game, Phaser.SpriteUtils.getAsPoints(atari)); - p2 = new Phaser.Polygon(game, Phaser.SpriteUtils.getAsPoints(atari2)); - - } - - function update() { - - atari.physics.acceleration.x = 0; - atari.physics.acceleration.y = 0; - - if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - atari.physics.acceleration.x = -150; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - atari.physics.acceleration.x = 150; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - atari.physics.acceleration.y = -150; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - atari.physics.acceleration.y = 150; - } - - } - - function render() { - - atari.physics.renderDebugInfo(16, 16); - - p.render(); - p2.render(); - - } - -})(); diff --git a/Tests/sprites/sprite origin 1.js b/Tests/sprites/sprite origin 1.js index 208f2489..ff8325ff 100644 --- a/Tests/sprites/sprite origin 1.js +++ b/Tests/sprites/sprite origin 1.js @@ -14,7 +14,7 @@ // The sprite is 320 x 200 pixels in size // If we don't set an origin then the sprite will rotate around 0,0 - the top left corner game.add.tween(fuji).to({ - rotation: 360 + angle: 360 }, 2000, Phaser.Easing.Linear.None, true, 0, true); } })(); diff --git a/Tests/sprites/sprite origin 1.ts b/Tests/sprites/sprite origin 1.ts index 145adc03..16a145b0 100644 --- a/Tests/sprites/sprite origin 1.ts +++ b/Tests/sprites/sprite origin 1.ts @@ -23,7 +23,7 @@ // The sprite is 320 x 200 pixels in size // If we don't set an origin then the sprite will rotate around 0,0 - the top left corner - game.add.tween(fuji).to({ rotation: 360 }, 2000, Phaser.Easing.Linear.None, true, 0, true); + game.add.tween(fuji).to({ angle: 360 }, 2000, Phaser.Easing.Linear.None, true, 0, true); } diff --git a/build/phaser-fx.d.ts b/build/phaser-fx.d.ts index 2a32af5d..3794a9b1 100644 --- a/build/phaser-fx.d.ts +++ b/build/phaser-fx.d.ts @@ -1,8 +1,3 @@ -/** -* Phaser - FX - Camera - Flash -* -* The camera is filled with the given color and returns to normal at the given duration. -*/ module Phaser.FX.Camera { class Flash { constructor(game: Game); @@ -11,95 +6,35 @@ module Phaser.FX.Camera { private _fxFlashComplete; private _fxFlashDuration; private _fxFlashAlpha; - /** - * The camera is filled with this color and returns to normal at the given duration. - * - * @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white. - * @param Duration How long it takes for the flash to fade. - * @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback. - * @param Force Force an already running flash effect to reset. - */ public start(color?: number, duration?: number, onComplete?, force?: bool): void; public postUpdate(): void; public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Border -* -* Creates a border around a camera. -*/ module Phaser.FX.Camera { class Border { constructor(game: Game, parent: Camera); private _game; private _parent; - /** - * Whether render border of this camera or not. (default is false) - * @type {boolean} - */ public showBorder: bool; - /** - * Color of border of this camera. (in css color string) - * @type {string} - */ public borderColor: string; - /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ public start(): void; - /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Template -* -* A Template FX file you can use to create your own Camera FX. -* If you don't use any of the methods below (i.e. preUpdate, render, etc) then DELETE THEM to avoid un-necessary calls by the FXManager. -*/ module Phaser.FX.Camera { class Template { constructor(game: Game, parent: Camera); private _game; private _parent; - /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ public start(): void; - /** - * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. - */ public preUpdate(): void; - /** - * Post-update is called at the end of the objects update cycle, after other update logic has taken place. - */ public postUpdate(): void; - /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - */ public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - */ public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Mirror -* -* Creates a mirror effect for a camera. -* Can mirror the camera image horizontally, vertically or both with an optional fill color overlay. -*/ module Phaser.FX.Camera { class Mirror { constructor(game: Game, parent: Camera); @@ -119,68 +54,24 @@ module Phaser.FX.Camera { public x: number; public y: number; public cls: bool; - /** - * This is the rectangular region to grab from the Camera used in the Mirror effect - * It is rendered to the Stage at Mirror.x/y (note the use of Stage coordinates, not World coordinates) - */ public start(x: number, y: number, region: Rectangle, fillColor?: string): void; - /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Shadow -* -* Creates a drop-shadow effect on the camera window. -*/ module Phaser.FX.Camera { class Shadow { constructor(game: Game, parent: Camera); private _game; private _parent; - /** - * Render camera shadow or not. (default is false) - * @type {boolean} - */ public showShadow: bool; - /** - * Color of shadow, in css color string. - * @type {string} - */ public shadowColor: string; - /** - * Blur factor of shadow. - * @type {number} - */ public shadowBlur: number; - /** - * Offset of the shadow from camera's position. - * @type {Point} - */ public shadowOffset: Point; - /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ public start(): void; - /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - */ public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; - /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - */ public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Scanlines -* -* Give your game that classic retro feel! -*/ module Phaser.FX.Camera { class Scanlines { constructor(game: Game, parent: Camera); @@ -191,11 +82,6 @@ module Phaser.FX.Camera { public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Shake -* -* A simple camera shake effect. -*/ module Phaser.FX.Camera { class Shake { constructor(game: Game, camera: Camera); @@ -211,25 +97,11 @@ module Phaser.FX.Camera { static SHAKE_BOTH_AXES: number; static SHAKE_HORIZONTAL_ONLY: number; static SHAKE_VERTICAL_ONLY: number; - /** - * A simple camera shake effect. - * - * @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking. - * @param Duration The length in seconds that the shaking effect should last. - * @param OnComplete A function you want to run when the shake effect finishes. - * @param Force Force the effect to reset (default = true, unlike flash() and fade()!). - * @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY). - */ public start(intensity?: number, duration?: number, onComplete?, force?: bool, direction?: number): void; public postUpdate(): void; public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; } } -/** -* Phaser - FX - Camera - Fade -* -* The camera is filled with the given color and returns to normal at the given duration. -*/ module Phaser.FX.Camera { class Fade { constructor(game: Game); @@ -238,14 +110,6 @@ module Phaser.FX.Camera { private _fxFadeComplete; private _fxFadeDuration; private _fxFadeAlpha; - /** - * The camera is gradually filled with this color. - * - * @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white. - * @param Duration How long it takes for the flash to fade. - * @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback. - * @param Force Force an already running flash effect to reset. - */ public start(color?: number, duration?: number, onComplete?, force?: bool): void; public postUpdate(): void; public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void; diff --git a/build/phaser-fx.js b/build/phaser-fx.js index 6499d8da..dc65ef51 100644 --- a/build/phaser-fx.js +++ b/build/phaser-fx.js @@ -1,12 +1,6 @@ var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Flash - * - * The camera is filled with the given color and returns to normal at the given duration. - */ (function (Camera) { var Flash = (function () { function Flash(game) { @@ -15,21 +9,12 @@ var Phaser; this._fxFlashAlpha = 0; this._game = game; } - Flash.prototype.start = /** - * The camera is filled with this color and returns to normal at the given duration. - * - * @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white. - * @param Duration How long it takes for the flash to fade. - * @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback. - * @param Force Force an already running flash effect to reset. - */ - function (color, duration, onComplete, force) { + Flash.prototype.start = function (color, duration, onComplete, force) { if (typeof color === "undefined") { color = 0xffffff; } if (typeof duration === "undefined") { duration = 1; } if (typeof onComplete === "undefined") { onComplete = null; } if (typeof force === "undefined") { force = false; } if(force === false && this._fxFlashAlpha > 0) { - // You can't flash again unless you force it return; } if(duration <= 0) { @@ -44,7 +29,6 @@ var Phaser; this._fxFlashComplete = onComplete; }; Flash.prototype.postUpdate = function () { - // Update the Flash effect if(this._fxFlashAlpha > 0) { this._fxFlashAlpha -= this._game.time.elapsed / this._fxFlashDuration; if(this._game.math.roundTo(this._fxFlashAlpha, -2) <= 0) { @@ -72,38 +56,17 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Border - * - * Creates a border around a camera. - */ (function (Camera) { var Border = (function () { function Border(game, parent) { - /** - * Whether render border of this camera or not. (default is false) - * @type {boolean} - */ this.showBorder = false; - /** - * Color of border of this camera. (in css color string) - * @type {string} - */ this.borderColor = 'rgb(255,255,255)'; this._game = game; this._parent = parent; } - Border.prototype.start = /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ - function () { + Border.prototype.start = function () { }; - Border.prototype.postRender = /** - * Post-render is called during the objects render cycle, after the children/image data has been rendered. - * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + Border.prototype.postRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { if(this.showBorder == true) { this._game.stage.context.strokeStyle = this.borderColor; this._game.stage.context.lineWidth = 1; @@ -122,50 +85,23 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Template - * - * A Template FX file you can use to create your own Camera FX. - * If you don't use any of the methods below (i.e. preUpdate, render, etc) then DELETE THEM to avoid un-necessary calls by the FXManager. - */ (function (Camera) { var Template = (function () { function Template(game, parent) { this._game = game; this._parent = parent; } - Template.prototype.start = /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ - function () { + Template.prototype.start = function () { }; - Template.prototype.preUpdate = /** - * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. - */ - function () { + Template.prototype.preUpdate = function () { }; - Template.prototype.postUpdate = /** - * Post-update is called at the end of the objects update cycle, after other update logic has taken place. - */ - function () { + Template.prototype.postUpdate = function () { }; - Template.prototype.preRender = /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + Template.prototype.preRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { }; - Template.prototype.render = /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + Template.prototype.render = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { }; - Template.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) { + Template.prototype.postRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { }; return Template; })(); @@ -178,13 +114,6 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Mirror - * - * Creates a mirror effect for a camera. - * Can mirror the camera image horizontally, vertically or both with an optional fill color overlay. - */ (function (Camera) { var Mirror = (function () { function Mirror(game, parent) { @@ -199,11 +128,7 @@ var Phaser; this._canvas.height = parent.height; this._context = this._canvas.getContext('2d'); } - Mirror.prototype.start = /** - * This is the rectangular region to grab from the Camera used in the Mirror effect - * It is rendered to the Stage at Mirror.x/y (note the use of Stage coordinates, not World coordinates) - */ - function (x, y, region, fillColor) { + Mirror.prototype.start = function (x, y, region, fillColor) { if (typeof fillColor === "undefined") { fillColor = 'rgba(0, 0, 100, 0.5)'; } this.x = x; this.y = y; @@ -216,15 +141,7 @@ var Phaser; this._context.fillStyle = this._mirrorColor; } }; - Mirror.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.cls) - //{ - // this._context.clearRect(0, 0, this._mirrorWidth, this._mirrorHeight); - //} + Mirror.prototype.postRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { this._sx = cameraX + this._mirrorX; this._sy = cameraY + this._mirrorY; if(this.flipX == true && this.flipY == false) { @@ -232,16 +149,7 @@ var Phaser; } else if(this.flipY == true && this.flipX == false) { this._sy = 0; } - this._context.drawImage(this._game.stage.canvas, // Source Image - this._sx, // Source X (location within the source image) - this._sy, // Source Y - this._mirrorWidth, // Source Width - this._mirrorHeight, // Source Height - 0, // Destination X (where on the canvas it'll be drawn) - 0, // Destination Y - this._mirrorWidth, // Destination Width (always same as Source Width unless scaled) - this._mirrorHeight); - // Destination Height (always same as Source Height unless scaled) + this._context.drawImage(this._game.stage.canvas, this._sx, this._sy, this._mirrorWidth, this._mirrorHeight, 0, 0, this._mirrorWidth, this._mirrorHeight); if(this._mirrorColor) { this._context.fillRect(0, 0, this._mirrorWidth, this._mirrorHeight); } @@ -267,49 +175,19 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Shadow - * - * Creates a drop-shadow effect on the camera window. - */ (function (Camera) { var Shadow = (function () { function Shadow(game, parent) { - /** - * Render camera shadow or not. (default is false) - * @type {boolean} - */ this.showShadow = false; - /** - * Color of shadow, in css color string. - * @type {string} - */ this.shadowColor = 'rgb(0,0,0)'; - /** - * Blur factor of shadow. - * @type {number} - */ this.shadowBlur = 10; - /** - * Offset of the shadow from camera's position. - * @type {Point} - */ this.shadowOffset = new Phaser.Point(4, 4); this._game = game; this._parent = parent; } - Shadow.prototype.start = /** - * You can name the function that starts the effect whatever you like, but we used 'start' in our effects. - */ - function () { + Shadow.prototype.start = function () { }; - Shadow.prototype.preRender = /** - * Pre-render is called at the start of the object render cycle, before any transforms have taken place. - * It happens directly AFTER a canvas context.save has happened if added to a Camera. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - // Shadow + Shadow.prototype.preRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { if(this.showShadow == true) { this._game.stage.context.shadowColor = this.shadowColor; this._game.stage.context.shadowBlur = this.shadowBlur; @@ -317,11 +195,7 @@ var Phaser; this._game.stage.context.shadowOffsetY = this.shadowOffset.y; } }; - Shadow.prototype.render = /** - * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. - */ - function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - // Shadow off + Shadow.prototype.render = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { if(this.showShadow == true) { this._game.stage.context.shadowBlur = 0; this._game.stage.context.shadowOffsetX = 0; @@ -339,12 +213,6 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Scanlines - * - * Give your game that classic retro feel! - */ (function (Camera) { var Scanlines = (function () { function Scanlines(game, parent) { @@ -370,12 +238,6 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Shake - * - * A simple camera shake effect. - */ (function (Camera) { var Shake = (function () { function Shake(game, camera) { @@ -392,16 +254,7 @@ var Phaser; Shake.SHAKE_BOTH_AXES = 0; Shake.SHAKE_HORIZONTAL_ONLY = 1; Shake.SHAKE_VERTICAL_ONLY = 2; - Shake.prototype.start = /** - * A simple camera shake effect. - * - * @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking. - * @param Duration The length in seconds that the shaking effect should last. - * @param OnComplete A function you want to run when the shake effect finishes. - * @param Force Force the effect to reset (default = true, unlike flash() and fade()!). - * @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY). - */ - function (intensity, duration, onComplete, force, direction) { + Shake.prototype.start = function (intensity, duration, onComplete, force, direction) { if (typeof intensity === "undefined") { intensity = 0.05; } if (typeof duration === "undefined") { duration = 0.5; } if (typeof onComplete === "undefined") { onComplete = null; } @@ -410,7 +263,6 @@ var Phaser; if(!force && ((this._fxShakeOffset.x != 0) || (this._fxShakeOffset.y != 0))) { return; } - // If a shake is not already running we need to store the offsets here if(this._fxShakeOffset.x == 0 && this._fxShakeOffset.y == 0) { this._fxShakePrevX = this._parent.x; this._fxShakePrevY = this._parent.y; @@ -422,7 +274,6 @@ var Phaser; this._fxShakeOffset.setTo(0, 0); }; Shake.prototype.postUpdate = function () { - // Update the "shake" special effect if(this._fxShakeDuration > 0) { this._fxShakeDuration -= this._game.time.elapsed; if(this._game.math.roundTo(this._fxShakeDuration, -2) <= 0) { @@ -435,11 +286,9 @@ var Phaser; } } else { if((this._fxShakeDirection == Shake.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Shake.SHAKE_HORIZONTAL_ONLY)) { - //this._fxShakeOffset.x = ((this._game.math.random() * this._fxShakeIntensity * this.worldView.width * 2 - this._fxShakeIntensity * this.worldView.width) * this._zoom; this._fxShakeOffset.x = (this._game.math.random() * this._fxShakeIntensity * this._parent.worldView.width * 2 - this._fxShakeIntensity * this._parent.worldView.width); } if((this._fxShakeDirection == Shake.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Shake.SHAKE_VERTICAL_ONLY)) { - //this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this.worldView.height * 2 - this._fxShakeIntensity * this.worldView.height) * this._zoom; this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this._parent.worldView.height * 2 - this._fxShakeIntensity * this._parent.worldView.height); } } @@ -462,12 +311,6 @@ var Phaser; var Phaser; (function (Phaser) { (function (FX) { - /// - /** - * Phaser - FX - Camera - Fade - * - * The camera is filled with the given color and returns to normal at the given duration. - */ (function (Camera) { var Fade = (function () { function Fade(game) { @@ -476,21 +319,12 @@ var Phaser; this._fxFadeAlpha = 0; this._game = game; } - Fade.prototype.start = /** - * The camera is gradually filled with this color. - * - * @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white. - * @param Duration How long it takes for the flash to fade. - * @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback. - * @param Force Force an already running flash effect to reset. - */ - function (color, duration, onComplete, force) { + Fade.prototype.start = function (color, duration, onComplete, force) { if (typeof color === "undefined") { color = 0x000000; } if (typeof duration === "undefined") { duration = 1; } if (typeof onComplete === "undefined") { onComplete = null; } if (typeof force === "undefined") { force = false; } if(force === false && this._fxFadeAlpha > 0) { - // You can't fade again unless you force it return; } if(duration <= 0) { @@ -505,7 +339,6 @@ var Phaser; this._fxFadeComplete = onComplete; }; Fade.prototype.postUpdate = function () { - // Update the Fade effect if(this._fxFadeAlpha > 0) { this._fxFadeAlpha += this._game.time.elapsed / this._fxFadeDuration; if(this._game.math.roundTo(this._fxFadeAlpha, -2) >= 1) { @@ -517,7 +350,6 @@ var Phaser; } }; Fade.prototype.postRender = function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { - // "Fade" FX if(this._fxFadeAlpha > 0) { this._game.stage.context.fillStyle = this._fxFadeColor + this._fxFadeAlpha + ')'; this._game.stage.context.fillRect(cameraX, cameraY, cameraWidth, cameraHeight); diff --git a/build/phaser.d.ts b/build/phaser.d.ts index 07065819..752795df 100644 --- a/build/phaser.d.ts +++ b/build/phaser.d.ts @@ -1,4 +1,1409 @@ /** +* Phaser - Point +* +* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. +*/ +module Phaser { + class Point { + /** + * Creates a new Point. If you pass no parameters a Point is created set to (0,0). + * @class Point + * @constructor + * @param {Number} x The horizontal position of this Point (default 0) + * @param {Number} y The vertical position of this Point (default 0) + **/ + constructor(x?: number, y?: number); + public x: number; + public y: number; + /** + * Copies the x and y properties from any given object to this Point. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Point} This Point object. + **/ + public copyFrom(source: any): Point; + /** + * Inverts the x and y values of this Point + * @method invert + * @return {Point} This Point object. + **/ + public invert(): Point; + /** + * Sets the x and y values of this MicroPoint object to the given coordinates. + * @method setTo + * @param {Number} x - The horizontal position of this point. + * @param {Number} y - The vertical position of this point. + * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. + **/ + public setTo(x: number, y: number): Point; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +/** +* Rectangle +* +* @desc A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. +* +* @version 1.6 - 24th May 2013 +* @author Richard Davey +*/ +module Phaser { + class Rectangle { + /** + * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. + * @class Rectangle + * @constructor + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + constructor(x?: number, y?: number, width?: number, height?: number); + /** + * The x coordinate of the top-left corner of the rectangle + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the top-left corner of the rectangle + * @property y + * @type Number + **/ + public y: number; + /** + * The width of the rectangle in pixels + * @property width + * @type Number + **/ + public width: number; + /** + * The height of the rectangle in pixels + * @property height + * @type Number + **/ + public height: number; + /** + * Half of the width of the rectangle + * @property halfWidth + * @type Number + **/ + public halfWidth : number; + /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + public halfHeight : number; + /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @return {Number} + **/ + /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @param {Number} value + **/ + public bottom : number; + /** + * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. + * @method bottomRight + * @param {Point} value + **/ + public bottomRight : Point; + /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @method left + * @ return {number} + **/ + /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. + * However it does affect the width, whereas changing the x value does not affect the width property. + * @method left + * @param {Number} value + **/ + public left : number; + /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @return {Number} + **/ + /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @param {Number} value + **/ + public right : number; + /** + * The volume of the Rectangle derived from width * height + * @method volume + * @return {Number} + **/ + public volume : number; + /** + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @method perimeter + * @return {Number} + **/ + public perimeter : number; + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @return {Number} + **/ + /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @param {Number} value + **/ + public top : number; + /** + * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. + * @method topLeft + * @param {Point} value + **/ + public topLeft : Point; + /** + * Determines whether or not this Rectangle object is empty. + * @method isEmpty + * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. + **/ + /** + * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. + * @method setEmpty + * @return {Rectangle} This rectangle object + **/ + public empty : bool; + /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Rectangle object by this amount. + * @param {Number} dy Moves the y value of the Rectangle object by this amount. + * @return {Rectangle} This Rectangle object. + **/ + public offset(dx: number, dy: number): Rectangle; + /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Rectangle object. + * @return {Rectangle} This Rectangle object. + **/ + public offsetPoint(point: Point): Rectangle; + /** + * Sets the members of Rectangle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + public setTo(x: number, y: number, width: number, height: number): Rectangle; + /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Rectangle} This Rectangle object. + **/ + public copyFrom(source: any): Rectangle; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +module Phaser { + interface IGameObject { + /** + * Reference to the main game object + */ + game: Game; + /** + * x value of the object. + */ + x: number; + /** + * y value of the object. + */ + y: number; + /** + * Z-order value of the object. + */ + z: number; + /** + * The type of game object. + */ + type: number; + /** + * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. + */ + render; + /** + * Controls if both update and render are called by the core game loop. + */ + exists: bool; + /** + * Controls if update() is automatically called by the core game loop. + */ + active: bool; + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + visible: bool; + /** + * The texture used to render the Sprite. + */ + texture: Components.Texture; + /** + * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. + */ + scale: Vec2; + /** + * The influence of camera movement upon the Sprite. + */ + scrollFactor: Vec2; + } +} +/** +* Phaser - LinkedList +* +* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! +*/ +module Phaser { + class LinkedList { + /** + * Creates a new link, and sets object and next to null. + */ + constructor(); + /** + * Stores a reference to an IGameObject. + */ + public object: IGameObject; + /** + * Stores a reference to the next link in the list. + */ + public next: LinkedList; + /** + * Clean up memory. + */ + public destroy(): void; + } +} +/** +* Phaser - QuadTree +* +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! +*/ +module Phaser { + class QuadTree extends Rectangle { + /** + * Instantiate a new Quad Tree node. + * + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. + */ + constructor(x: number, y: number, width: number, height: number, parent?: QuadTree); + private _iterator; + private _ot; + private _i; + private _basic; + private _members; + private _l; + private _overlapProcessed; + private _checkObject; + /** + * Flag for specifying that you want to add an object to the A list. + */ + static A_LIST: number; + /** + * Flag for specifying that you want to add an object to the B list. + */ + static B_LIST: number; + /** + * Controls the granularity of the quad tree. Default is 6 (decent performance on large and small worlds). + */ + static divisions: number; + /** + * Whether this branch of the tree can be subdivided or not. + */ + private _canSubdivide; + /** + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. + */ + private _headA; + /** + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. + */ + private _tailA; + /** + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. + */ + private _headB; + /** + * Refers to the internal A and B linked lists, + * which are used to store objects in the leaves. + */ + private _tailB; + /** + * Internal, governs and assists with the formation of the tree. + */ + private static _min; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _northWestTree; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _northEastTree; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _southEastTree; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _southWestTree; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _leftEdge; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _rightEdge; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _topEdge; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _bottomEdge; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _halfWidth; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _halfHeight; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _midpointX; + /** + * Internal, governs and assists with the formation of the tree. + */ + private _midpointY; + /** + * Internal, used to reduce recursive method parameters during object placement and tree formation. + */ + private static _object; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _list; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _useBothLists; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _processingCallback; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _notifyCallback; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _callbackContext; + /** + * Internal, used during tree processing and overlap checks. + */ + private static _iterator; + /** + * Clean up memory. + */ + public destroy(): void; + /** + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called + */ + public load(objectOrGroup1, objectOrGroup2?, notifyCallback?, processCallback?, context?): void; + /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + public add(objectOrGroup, list: number): void; + /** + * Internal function for recursively navigating and creating the tree + * while adding objects to the appropriate nodes. + */ + private addObject(); + /** + * Internal function for recursively adding objects to leaf lists. + */ + private addToList(); + /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + public execute(): bool; + /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + private overlapNode(); + } +} +/** +* Phaser - Vec2 +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +module Phaser { + class Vec2 { + /** + * Creates a new Vec2 object. + * @class Vec2 + * @constructor + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + constructor(x?: number, y?: number); + /** + * The x coordinate of the vector + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the vector + * @property y + * @type Number + **/ + public y: number; + /** + * Copies the x and y properties from any given object to this Vec2. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Vec2} This Vec2 object. + **/ + public copyFrom(source: any): Vec2; + /** + * Sets the x and y properties of the Vector. + * @param {Number} x The x position of the vector + * @param {Number} y The y position of the vector + * @return {Vec2} This object + **/ + public setTo(x: number, y: number): Vec2; + /** + * Add another vector to this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public add(a: Vec2): Vec2; + /** + * Subtract another vector from this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public subtract(v: Vec2): Vec2; + /** + * Multiply another vector with this one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public multiply(v: Vec2): Vec2; + /** + * Divide this vector by another one. + * + * @param {Vec2} other The other Vector. + * @return {Vec2} This for chaining. + */ + public divide(v: Vec2): Vec2; + /** + * Get the length of this vector. + * + * @return {number} The length of this vector. + */ + public length(): number; + /** + * Get the length squared of this vector. + * + * @return {number} The length^2 of this vector. + */ + public lengthSq(): number; + /** + * The dot product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public dot(a: Vec2): number; + /** + * The cross product of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public cross(a: Vec2): number; + /** + * The projection magnitude of two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public projectionLength(a: Vec2): number; + /** + * The angle between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @return {Number} + */ + public angle(a: Vec2): number; + /** + * Scale this vector. + * + * @param {number} x The scaling factor in the x direction. + * @param {?number=} y The scaling factor in the y direction. If this is not specified, the x scaling factor will be used. + * @return {Vec2} This for chaining. + */ + public scale(x: number, y?: number): Vec2; + /** + * Multiply this vector by the given scalar. + * + * @param {number} scalar + * @return {Vec2} This for chaining. + */ + public multiplyByScalar(scalar: number): Vec2; + /** + * Divide this vector by the given scalar. + * + * @param {number} scalar + * @return {Vec2} This for chaining. + */ + public divideByScalar(scalar: number): Vec2; + /** + * Reverse this vector. + * + * @return {Vec2} This for chaining. + */ + public reverse(): Vec2; + /** + * Check if both the x and y of this vector equal the given value. + * + * @return {Boolean} + */ + public equals(value): bool; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + public toString(): string; + } +} +/** +* Phaser - Circle +* +* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. +*/ +module Phaser { + class Circle { + /** + * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. + * @class Circle + * @constructor + * @param {Number} [x] The x coordinate of the center of the circle. + * @param {Number} [y] The y coordinate of the center of the circle. + * @param {Number} [diameter] The diameter of the circle. + * @return {Circle} This circle object + **/ + constructor(x?: number, y?: number, diameter?: number); + private _diameter; + private _radius; + /** + * The x coordinate of the center of the circle + * @property x + * @type Number + **/ + public x: number; + /** + * The y coordinate of the center of the circle + * @property y + * @type Number + **/ + public y: number; + /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @return {Number} + **/ + /** + * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. + * @method diameter + * @param {Number} The diameter of the circle. + **/ + public diameter : number; + /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @return {Number} + **/ + /** + * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. + * @method radius + * @param {Number} The radius of the circle. + **/ + public radius : number; + /** + * The circumference of the circle. + * @method circumference + * @return {Number} + **/ + public circumference(): number; + /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + /** + * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The value to adjust the height of the circle by. + **/ + public bottom : number; + /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @return {Number} The x coordinate of the leftmost point of the circle. + **/ + /** + * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method left + * @param {Number} The value to adjust the position of the leftmost point of the circle by. + **/ + public left : number; + /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @return {Number} + **/ + /** + * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. + * @method right + * @param {Number} The amount to adjust the diameter of the circle by. + **/ + public right : number; + /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @return {Number} + **/ + /** + * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. + * @method bottom + * @param {Number} The amount to adjust the height of the circle by. + **/ + public top : number; + /** + * Gets the area of this Circle. + * @method area + * @return {Number} This area of this circle. + **/ + public area : number; + /** + * Sets the members of Circle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the center of the circle. + * @param {Number} y The y coordinate of the center of the circle. + * @param {Number} diameter The diameter of the circle in pixels. + * @return {Circle} This circle object + **/ + public setTo(x: number, y: number, diameter: number): Circle; + /** + * Copies the x, y and diameter properties from any given object to this Circle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Circle} This Circle object. + **/ + public copyFrom(source: any): Circle; + /** + * Determines whether or not this Circle object is empty. + * @method empty + * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. + **/ + /** + * Sets all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. + * @method setEmpty + * @return {Circle} This Circle object + **/ + public empty : bool; + /** + * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Circle object by this amount. + * @param {Number} dy Moves the y value of the Circle object by this amount. + * @return {Circle} This Circle object. + **/ + public offset(dx: number, dy: number): Circle; + /** + * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Circle object. + * @return {Circle} This Circle object. + **/ + public offsetPoint(point: Point): Circle; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + public toString(): string; + } +} +module Phaser { + /** + * Constants used to define game object types (faster than doing typeof object checks in core loops) + */ + class Types { + static RENDERER_AUTO_DETECT: number; + static RENDERER_HEADLESS: number; + static RENDERER_CANVAS: number; + static RENDERER_WEBGL: number; + static GROUP: number; + static SPRITE: number; + static GEOMSPRITE: number; + static PARTICLE: number; + static EMITTER: number; + static TILEMAP: number; + static SCROLLZONE: number; + static GEOM_POINT: number; + static GEOM_CIRCLE: number; + static GEOM_RECTANGLE: number; + static GEOM_LINE: number; + static GEOM_POLYGON: number; + static BODY_DISABLED: number; + static BODY_DYNAMIC: number; + static BODY_STATIC: number; + static BODY_KINEMATIC: number; + /** + * Flag used to allow GameObjects to collide on their left side + * @type {number} + */ + static LEFT: number; + /** + * Flag used to allow GameObjects to collide on their right side + * @type {number} + */ + static RIGHT: number; + /** + * Flag used to allow GameObjects to collide on their top side + * @type {number} + */ + static UP: number; + /** + * Flag used to allow GameObjects to collide on their bottom side + * @type {number} + */ + static DOWN: number; + /** + * Flag used with GameObjects to disable collision + * @type {number} + */ + static NONE: number; + /** + * Flag used to allow GameObjects to collide with a ceiling + * @type {number} + */ + static CEILING: number; + /** + * Flag used to allow GameObjects to collide with a floor + * @type {number} + */ + static FLOOR: number; + /** + * Flag used to allow GameObjects to collide with a wall (same as LEFT+RIGHT) + * @type {number} + */ + static WALL: number; + /** + * Flag used to allow GameObjects to collide on any face + * @type {number} + */ + static ANY: number; + } +} +/** +* Phaser - Group +* +* This class is used for organising, updating and sorting game objects. +*/ +module Phaser { + class Group { + constructor(game: Game, maxSize?: number); + /** + * Internal tracker for the maximum capacity of the group. + * Default is 0, or no max capacity. + */ + private _maxSize; + /** + * Internal helper variable for recycling objects a la Emitter. + */ + private _marker; + /** + * Helper for sort. + */ + private _sortIndex; + /** + * Helper for sort. + */ + private _sortOrder; + /** + * Temp vars to help avoid gc spikes + */ + private _member; + private _length; + private _i; + private _prevAlpha; + private _count; + /** + * Reference to the main game object + */ + public game: Game; + /** + * The type of game object. + */ + public type: number; + /** + * If this Group exists or not. Can be set to false to skip certain loop checks. + */ + public exists: bool; + /** + * Controls if this Group (and all of its contents) are rendered or skipped during the core game loop. + */ + public visible: bool; + /** + * Use with sort() to sort in ascending order. + */ + static ASCENDING: number; + /** + * Use with sort() to sort in descending order. + */ + static DESCENDING: number; + /** + * Array of all the objects that exist in this group. + */ + public members; + /** + * The number of entries in the members array. + * For performance and safety you should check this variable + * instead of members.length unless you really know what you're doing! + */ + public length: number; + /** + * 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. + * If this value is set it will call a canvas context save and restore before and after the render pass. + * Set to null to disable. + */ + public globalCompositeOperation: string; + /** + * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. + * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. + * Set to 0 to disable. + */ + public alpha: number; + /** + * An Array of Cameras to which this Group, or any of its children, won't render + * @type {Array} + */ + public cameraBlacklist: number[]; + /** + * Override this function to handle any deleting or "shutdown" type operations you might need, + * such as removing traditional Flash children like Basic objects. + */ + public destroy(): void; + /** + * 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(): void; + /** + * 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(renderer: IRenderer, camera: Camera): void; + /** + * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. + */ + /** + * @private + */ + public maxSize : number; + /** + * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. + * Group will try to replace a null member of the array first. + * Failing that, Group will add it to the end of the member array, + * assuming there is room for it, and doubling the size of the array if necessary. + * + *

WARNING: If the group has a maxSize that has already been met, + * the object will NOT be added to the group!

+ * + * @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): any; + /** + * Recycling is designed to help you reuse game objects without always re-allocating or "newing" them. + * + *

If you specified a maximum size for this group (like in Emitter), + * then recycle will employ what we're calling "rotating" recycling. + * Recycle() will first check to see if the group is at capacity yet. + * If group is not yet at capacity, recycle() returns a new object. + * If the group IS at capacity, then recycle() just returns the next object in line.

+ * + *

If you did NOT specify a maximum size for this group, + * then recycle() will employ what we're calling "grow-style" recycling. + * Recycle() will return either the first object with exists == false, + * or, finding none, add a new object to the array, + * doubling the size of the array if necessary.

+ * + *

WARNING: If this function needs to create a new object, + * and no object class was provided, it will return null + * instead of a valid object!

+ * + * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! + * + * @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?); + /** + * Removes an object from the group. + * + * @param {Basic} object The Basic you want to remove. + * @param {boolean} splice Whether the object should be cut from the array entirely or not. + * + * @return {Basic} The removed object. + */ + public remove(object, splice?: bool); + /** + * Replaces an existing Basic with a new one. + * + * @param {Basic} oldObject The object you want to replace. + * @param {Basic} newObject The new object you want to use instead. + * + * @return {Basic} The new object. + */ + public replace(oldObject, newObject); + /** + * Call this function to sort the group according to a particular value and order. + * For example, to sort game objects for Zelda-style overlaps you might call + * myGroup.sort("y",Group.ASCENDING) at the bottom of your + * State.update() override. To sort all existing objects after + * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). + * + * @param {string} index The string name of the member variable you want to sort on. Default value is "y". + * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. + */ + public sort(index?: string, order?: number): void; + /** + * Go through and set the specified variable to the specified value on all members of the group. + * + * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". + * @param {Object} Value The value you want to assign to that variable. + * @param {boolean} Recurse Default value is true, meaning if setAll() encounters a member that is a group, it will call setAll() on that group rather than modifying its variable. + */ + public setAll(variableName: string, value: Object, recurse?: bool): void; + /** + * Go through and call the specified function on all members of the group. + * Currently only works on functions that have no required parameters. + * + * @param {string} FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()". + * @param {boolean} Recurse Default value is true, meaning if callAll() encounters a member that is a group, it will call callAll() on that group rather than calling the group's function. + */ + public callAll(functionName: string, recurse?: bool): void; + /** + * @param {function} callback + * @param {boolean} recursive + */ + public forEach(callback, recursive?: bool): void; + /** + * @param {any} context + * @param {function} callback + * @param {boolean} recursive + */ + public forEachAlive(context, callback, recursive?: bool): void; + /** + * Call this function to retrieve the first object with exists == false in the group. + * This is handy for recycling in general, e.g. respawning enemies. + * + * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. + * + * @return {any} A Basic currently flagged as not existing. + */ + public getFirstAvailable(objectClass?); + /** + * Call this function to retrieve the first index set to 'null'. + * Returns -1 if no index stores a null object. + * + * @return {number} An int indicating the first null slot in the group. + */ + public getFirstNull(): number; + /** + * Call this function to retrieve the first object with exists == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as existing. + */ + public getFirstExtant(); + /** + * Call this function to retrieve the first object with dead == false in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as not dead. + */ + public getFirstAlive(); + /** + * Call this function to retrieve the first object with dead == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as dead. + */ + public getFirstDead(); + /** + * Call this function to find out how many members of the group are not dead. + * + * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. + */ + public countLiving(): number; + /** + * Call this function to find out how many members of the group are dead. + * + * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. + */ + public countDead(): number; + /** + * Returns a member at random from the group. + * + * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {number} Length Optional restriction on the number of values you want to randomly select from. + * + * @return {Basic} A Basic from the members list. + */ + public getRandom(startIndex?: number, length?: number); + /** + * Remove all instances of Basic subclass (Basic, Block, etc) from the list. + * WARNING: does not destroy() or kill() any of these objects! + */ + public clear(): void; + /** + * Calls kill on the group's members and then on the group itself. + */ + public kill(): void; + /** + * Helper function for the sort process. + * + * @param {Basic} Obj1 The first object being sorted. + * @param {Basic} Obj2 The second object being sorted. + * + * @return {number} An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2). + */ + public sortHandler(obj1, obj2): number; + } +} +/** +* Phaser - SignalBinding +* +* An object that represents a binding between a Signal and a listener function. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ +*/ +module Phaser { + class SignalBinding { + /** + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {boolean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). + */ + constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number); + /** + * Handler function bound to the signal. + * @type Function + * @private + */ + private _listener; + /** + * If binding should be executed just once. + * @type boolean + * @private + */ + private _isOnce; + /** + * Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @memberOf SignalBinding.prototype + * @name context + * @type Object|undefined|null + */ + public context; + /** + * Reference to Signal object that listener is currently bound to. + * @type Signal + * @private + */ + private _signal; + /** + * Listener priority + * @type Number + */ + public priority: number; + /** + * If binding is active and should be executed. + * @type boolean + */ + public active: bool; + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + public params; + /** + * Call listener passing arbitrary parameters. + *

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

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

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

+ * @type boolean + */ + public active: bool; + /** + * + * @method validateListener + * @param {Any} listener + * @param {Any} fnName + */ + public validateListener(listener, fnName): void; + /** + * @param {Function} listener + * @param {boolean} isOnce + * @param {Object} [listenerContext] + * @param {Number} [priority] + * @return {SignalBinding} + * @private + */ + private _registerListener(listener, isOnce, listenerContext, priority); + /** + * + * @method _addBinding + * @param {SignalBinding} binding + * @private + */ + private _addBinding(binding); + /** + * + * @method _indexOfListener + * @param {Function} listener + * @return {number} + * @private + */ + private _indexOfListener(listener, context); + /** + * Check if listener was attached to Signal. + * @param {Function} listener + * @param {Object} [context] + * @return {boolean} if Signal has the specified listener. + */ + public has(listener, context?: any): bool; + /** + * Add a listener to the signal. + * @param {Function} listener Signal handler function. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + * @return {SignalBinding} An Object representing the binding between the Signal and listener. + */ + public add(listener, listenerContext?: any, priority?: number): SignalBinding; + /** + * Add listener to the signal that should be removed after first execution (will be executed only once). + * @param {Function} listener Signal handler function. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) + * @return {SignalBinding} An Object representing the binding between the Signal and listener. + */ + public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding; + /** + * Remove a single listener from the dispatch queue. + * @param {Function} listener Handler function that should be removed. + * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). + * @return {Function} Listener handler function. + */ + public remove(listener, context?: any); + /** + * Remove all listeners from the Signal. + */ + public removeAll(): void; + /** + * @return {number} Number of listeners attached to the Signal. + */ + public getNumListeners(): number; + /** + * Stop propagation of the event, blocking the dispatch to next listeners on the queue. + *

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

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

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

+ */ + public dispose(): void; + /** + * @return {string} String representation of the object. + */ + public toString(): string; + } +} +/** * Phaser - Loader * * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. @@ -304,7 +1709,7 @@ module Phaser { module Phaser { class GameMath { constructor(game: Game); - private _game; + public game: Game; static PI: number; static PI_2: number; static PI_4: number; @@ -647,21 +2052,21 @@ module Phaser { * @method linear * @param {Any} v * @param {Any} k - * @static + * @public */ public linearInterpolation(v, k); /** * @method Bezier * @param {Any} v * @param {Any} k - * @static + * @public */ public bezierInterpolation(v, k): number; /** * @method CatmullRom * @param {Any} v * @param {Any} k - * @static + * @public */ public catmullRomInterpolation(v, k); /** @@ -669,14 +2074,14 @@ module Phaser { * @param {Any} p0 * @param {Any} p1 * @param {Any} t - * @static + * @public */ public linear(p0, p1, t); /** * @method Bernstein * @param {Any} n * @param {Any} i - * @static + * @public */ public bernstein(n, i): number; /** @@ -686,7 +2091,7 @@ module Phaser { * @param {Any} p2 * @param {Any} p3 * @param {Any} t - * @static + * @public */ public catmullRom(p0, p1, p2, p3, t); public difference(a: number, b: number): number; @@ -764,26 +2169,6 @@ module Phaser { */ public shiftCosTable(): number; /** - * Finds the length of the given vector - * - * @param dx - * @param dy - * - * @return - */ - public vectorLength(dx: number, dy: number): number; - /** - * Finds the dot product value of two vectors - * - * @param ax Vector X - * @param ay Vector Y - * @param bx Vector X - * @param by Vector Y - * - * @return Dot product - */ - public dotProduct(ax: number, ay: number, bx: number, by: number): number; - /** * Shuffles the data in the given array into a new order * @param array The array to shuffle * @return The array @@ -796,7 +2181,16 @@ module Phaser { * @param {Boolean} round - Round the distance to the nearest integer (default false) * @return {Number} The distance between this Point object and the destination Point object. **/ - static distanceBetween(x1: number, y1: number, x2: number, y2: number): number; + public distanceBetween(x1: number, y1: number, x2: number, y2: number): number; + /** + * Finds the length of the given vector + * + * @param dx + * @param dy + * + * @return + */ + public vectorLength(dx: number, dy: number): number; /** * Rotates the point around the x/y coordinates given to the desired angle and distance * @param point {Object} Any object with exposed x and y properties @@ -949,233 +2343,6 @@ module 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. -*/ -module Phaser { - class Point { - /** - * Creates a new Point. If you pass no parameters a Point is created set to (0,0). - * @class Point - * @constructor - * @param {Number} x The horizontal position of this Point (default 0) - * @param {Number} y The vertical position of this Point (default 0) - **/ - constructor(x?: number, y?: number); - public x: number; - public y: number; - /** - * Copies the x and y properties from any given object to this Point. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Point} This Point object. - **/ - public copyFrom(source: any): Point; - /** - * Inverts the x and y values of this Point - * @method invert - * @return {Point} This Point object. - **/ - public invert(): Point; - /** - * Sets the x and y values of this MicroPoint object to the given coordinates. - * @method setTo - * @param {Number} x - The horizontal position of this point. - * @param {Number} y - The vertical position of this point. - * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. - **/ - public setTo(x: number, y: number): Point; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** -* Rectangle -* -* @desc A Rectangle object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. -* -* @version 1.6 - 24th May 2013 -* @author Richard Davey -*/ -module Phaser { - class Rectangle { - /** - * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. - * @class Rectangle - * @constructor - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - constructor(x?: number, y?: number, width?: number, height?: number); - /** - * The x coordinate of the top-left corner of the rectangle - * @property x - * @type Number - **/ - public x: number; - /** - * The y coordinate of the top-left corner of the rectangle - * @property y - * @type Number - **/ - public y: number; - /** - * The width of the rectangle in pixels - * @property width - * @type Number - **/ - public width: number; - /** - * The height of the rectangle in pixels - * @property height - * @type Number - **/ - public height: number; - /** - * Half of the width of the rectangle - * @property halfWidth - * @type Number - **/ - public halfWidth : number; - /** - * Half of the height of the rectangle - * @property halfHeight - * @type Number - **/ - public halfHeight : number; - /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @return {Number} - **/ - /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @param {Number} value - **/ - public bottom : number; - /** - * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. - * @method bottomRight - * @param {Point} value - **/ - public bottomRight : Point; - /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @ return {number} - **/ - /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width, whereas changing the x value does not affect the width property. - * @method left - * @param {Number} value - **/ - public left : number; - /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {Number} - **/ - /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {Number} value - **/ - public right : number; - /** - * The volume of the Rectangle derived from width * height - * @method volume - * @return {Number} - **/ - public volume : number; - /** - * The perimeter size of the Rectangle. This is the sum of all 4 sides. - * @method perimeter - * @return {Number} - **/ - public perimeter : number; - /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @return {Number} - **/ - /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @param {Number} value - **/ - public top : number; - /** - * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. - * @method topLeft - * @param {Point} value - **/ - public topLeft : Point; - /** - * Determines whether or not this Rectangle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. - **/ - /** - * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. - * @method setEmpty - * @return {Rectangle} This rectangle object - **/ - public empty : bool; - /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Rectangle object by this amount. - * @param {Number} dy Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - public offset(dx: number, dy: number): Rectangle; - /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - public offsetPoint(point: Point): Rectangle; - /** - * Sets the members of Rectangle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - public setTo(x: number, y: number, width: number, height: number): Rectangle; - /** - * Copies the x, y, width and height properties from any given object to this Rectangle. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Rectangle} This Rectangle object. - **/ - public copyFrom(source: any): Rectangle; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** * Phaser - AnimationLoader * * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. @@ -1724,58 +2891,6 @@ module Phaser { static union(a: Rectangle, b: Rectangle, out?: Rectangle): Rectangle; } } -module Phaser { - interface IGameObject { - /** - * Reference to the main game object - */ - game: Game; - /** - * x value of the object. - */ - x: number; - /** - * y value of the object. - */ - y: number; - /** - * Z-order value of the object. - */ - z: number; - /** - * The type of game object. - */ - type: number; - /** - * Reference to the Renderer.renderSprite method. Can be overriden by custom classes. - */ - render; - /** - * Controls if both update and render are called by the core game loop. - */ - exists: bool; - /** - * Controls if update() is automatically called by the core game loop. - */ - active: bool; - /** - * Controls if this Sprite is rendered or skipped during the core game loop. - */ - visible: bool; - /** - * The texture used to render the Sprite. - */ - texture: Components.Texture; - /** - * Scale of the Sprite. A scale of 1.0 is the original size. 0.5 half size. 2.0 double sized. - */ - scale: Vec2; - /** - * The influence of camera movement upon the Sprite. - */ - scrollFactor: Vec2; - } -} /** * Phaser - DynamicTexture * @@ -1925,220 +3040,46 @@ module Phaser { } } /** -* Phaser - Circle -* -* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. -*/ -module Phaser { - class Circle { - /** - * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. - * @class Circle - * @constructor - * @param {Number} [x] The x coordinate of the center of the circle. - * @param {Number} [y] The y coordinate of the center of the circle. - * @param {Number} [diameter] The diameter of the circle. - * @return {Circle} This circle object - **/ - constructor(x?: number, y?: number, diameter?: number); - private _diameter; - private _radius; - /** - * The x coordinate of the center of the circle - * @property x - * @type Number - **/ - public x: number; - /** - * The y coordinate of the center of the circle - * @property y - * @type Number - **/ - public y: number; - /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @return {Number} - **/ - /** - * The diameter of the circle. The largest distance between any two points on the circle. The same as the radius * 2. - * @method diameter - * @param {Number} The diameter of the circle. - **/ - public diameter : number; - /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @return {Number} - **/ - /** - * The radius of the circle. The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. - * @method radius - * @param {Number} The radius of the circle. - **/ - public radius : number; - /** - * The circumference of the circle. - * @method circumference - * @return {Number} - **/ - public circumference(): number; - /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - /** - * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The value to adjust the height of the circle by. - **/ - public bottom : number; - /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @return {Number} The x coordinate of the leftmost point of the circle. - **/ - /** - * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method left - * @param {Number} The value to adjust the position of the leftmost point of the circle by. - **/ - public left : number; - /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @return {Number} - **/ - /** - * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. - * @method right - * @param {Number} The amount to adjust the diameter of the circle by. - **/ - public right : number; - /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @return {Number} - **/ - /** - * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. - * @method bottom - * @param {Number} The amount to adjust the height of the circle by. - **/ - public top : number; - /** - * Gets the area of this Circle. - * @method area - * @return {Number} This area of this circle. - **/ - public area : number; - /** - * Sets the members of Circle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the center of the circle. - * @param {Number} y The y coordinate of the center of the circle. - * @param {Number} diameter The diameter of the circle in pixels. - * @return {Circle} This circle object - **/ - public setTo(x: number, y: number, diameter: number): Circle; - /** - * Copies the x, y and diameter properties from any given object to this Circle. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Circle} This Circle object. - **/ - public copyFrom(source: any): Circle; - /** - * Determines whether or not this Circle object is empty. - * @method empty - * @return {Boolean} A value of true if the Circle objects diameter is less than or equal to 0; otherwise false. - **/ - /** - * Sets all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. - * @method setEmpty - * @return {Circle} This Circle object - **/ - public empty : bool; - /** - * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Circle object by this amount. - * @param {Number} dy Moves the y value of the Circle object by this amount. - * @return {Circle} This Circle object. - **/ - public offset(dx: number, dy: number): Circle; - /** - * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Circle object. - * @return {Circle} This Circle object. - **/ - public offsetPoint(point: Point): Circle; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - public toString(): string; - } -} -/** * Phaser - SpriteUtils * * A collection of methods useful for manipulating and checking Sprites. -* -* TODO: */ module Phaser { class SpriteUtils { - /** - * Pivot position enum: at the top-left corner. - * @type {number} - */ - static ALIGN_TOP_LEFT: number; - /** - * Pivot position enum: at the top-center corner. - * @type {number} - */ - static ALIGN_TOP_CENTER: number; - /** - * Pivot position enum: at the top-right corner. - * @type {number} - */ - static ALIGN_TOP_RIGHT: number; - /** - * Pivot position enum: at the center-left corner. - * @type {number} - */ - static ALIGN_CENTER_LEFT: number; - /** - * Pivot position enum: at the center corner. - * @type {number} - */ - static ALIGN_CENTER: number; - /** - * Pivot position enum: at the center-right corner. - * @type {number} - */ - static ALIGN_CENTER_RIGHT: number; - /** - * Pivot position enum: at the bottom-left corner. - * @type {number} - */ - static ALIGN_BOTTOM_LEFT: number; - /** - * Pivot position enum: at the bottom-center corner. - * @type {number} - */ - static ALIGN_BOTTOM_CENTER: number; - /** - * Pivot position enum: at the bottom-right corner. - * @type {number} - */ - static ALIGN_BOTTOM_RIGHT: number; + static _tempPoint: Point; static getAsPoints(sprite: Sprite): Point[]; /** + * 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(sprite: Sprite, camera?: Camera): bool; + /** + * Call this to figure out the on-screen position of the object. + * + * @param point {Point} Takes a MicroPoint object and assigns the post-scrolled X and Y values of this object to it. + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {Point} The Point 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(sprite: Sprite, point?: Point, camera?: Camera): Point; + /** + * 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; + /** + * 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(sprite: Sprite, x: number, y: number): void; + /** * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) * it can be stopped from leaving the world, or a section of it. @@ -2257,6 +3198,251 @@ module Phaser.Components { } } /** +* Phaser - Vec2Utils +* +* A collection of methods useful for manipulating and performing operations on 2D vectors. +* +*/ +module Phaser { + class Vec2Utils { + /** + * 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. + */ + static add(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static subtract(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static multiply(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static divide(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static scale(a: Vec2, s: number, out?: Vec2): Vec2; + /** + * 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. + */ + static perp(a: Vec2, out?: Vec2): Vec2; + /** + * 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} + */ + static equals(a: Vec2, b: Vec2): bool; + /** + * + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} epsilon + * @return {Boolean} + */ + static epsilonEquals(a: Vec2, b: Vec2, epsilon: number): bool; + /** + * 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} + */ + static distance(a: Vec2, b: Vec2): number; + /** + * Get the distance squared between two 2D vectors. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @return {Number} + */ + static distanceSq(a: Vec2, b: Vec2): number; + /** + * Project two 2D vectors onto another vector. + * + * @param {Vec2} a Reference to a source Vec2 object. + * @param {Vec2} b Reference to a source Vec2 object. + * @param {Vec2} out The output Vec2 that is the result of the operation. + * @return {Vec2} A Vec2. + */ + static project(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static projectUnit(a: Vec2, b: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static normalRightHand(a: Vec2, out?: Vec2): Vec2; + /** + * 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. + */ + static normalize(a: Vec2, out?: Vec2): Vec2; + /** + * 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} + */ + static dot(a: Vec2, b: Vec2): number; + /** + * 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} + */ + static cross(a: Vec2, b: Vec2): number; + /** + * 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} + */ + static angle(a: Vec2, b: Vec2): number; + /** + * 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} + */ + static angleSq(a: Vec2, b: Vec2): number; + /** + * 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. + */ + static rotate(a: Vec2, b: Vec2, theta: number, out?: Vec2): Vec2; + /** + * 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. + */ + static clone(a: Vec2, out?: Vec2): Vec2; + } +} +/** +* Phaser - Physics - Body +*/ +module Phaser.Physics { + class Body { + constructor(parent: Sprite, type: number); + public game: Game; + public parent: Sprite; + /** + * The type of Body (disabled, dynamic, static or kinematic) + * Disabled = skips all physics operations / tests (default) + * Dynamic = gives and receives impacts + * Static = gives but doesn't receive impacts, cannot be moved by physics + * Kinematic = gives impacts, but never receives, can be moved by physics + * @type {number} + */ + public type: number; + public gravity: Vec2; + public bounce: Vec2; + public velocity: Vec2; + public acceleration: Vec2; + public drag: Vec2; + public maxVelocity: Vec2; + public angularVelocity: number; + public angularAcceleration: number; + public angularDrag: number; + public maxAngular: number; + /** + * Angle of rotation of this body. + * @type {number} + */ + public angle: number; + /** + * Orientation of the object. + * @type {number} + */ + public facing: number; + public touching: number; + public allowCollisions: number; + public wasTouching: number; + public mass: number; + public position: Vec2; + public oldPosition: Vec2; + public offset: Vec2; + public bounds: Rectangle; + public preUpdate(): void; + public postUpdate(): void; + public hullWidth : number; + public hullHeight : number; + public hullX : number; + public hullY : number; + public deltaXAbs : number; + public deltaYAbs : number; + public deltaX : number; + public deltaY : number; + public render(context: CanvasRenderingContext2D): void; + /** + * Render debug infos. (including name, bounds info, position and some other properties) + * @param x {number} X position of the debug info to be rendered. + * @param y {number} Y position of the debug info to be rendered. + * @param [color] {number} color of the debug info to be rendered. (format is css color string) + */ + public renderDebugInfo(x: number, y: number, color?: string): void; + } +} +/** * Phaser - Sprite * */ @@ -2269,15 +3455,9 @@ module Phaser { * @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. + * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) */ - constructor(game: Game, x?: number, y?: number, key?: string, width?: number, height?: number); - /** - * Rotation angle of this object. - * @type {number} - */ - private _rotation; + constructor(game: Game, x?: number, y?: number, key?: string, bodyType?: number); /** * Reference to the main game object */ @@ -2307,9 +3487,9 @@ module Phaser { */ public alive: bool; /** - * Sprite physics. + * Sprite physics body. */ - public physics: Components.Physics; + public body: Physics.Body; /** * The texture used to render the Sprite. */ @@ -2320,6 +3500,11 @@ module Phaser { */ public animations: Components.AnimationManager; /** + * An Array of Cameras to which this GameObject won't render + * @type {Array} + */ + public cameraBlacklist: number[]; + /** * 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. @@ -2358,20 +3543,20 @@ module Phaser { */ public z: number; /** - * This value is added to the rotation of the Sprite. + * This value is added to the angle 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. + * angleOffset to 90 and it would correspond correctly with Phasers right-handed coordinate system. * @type {number} */ - public rotationOffset: number; + public angleOffset: number; /** - * The rotation of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. + * The angle of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. */ /** - * Set the rotation of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. + * Set the angle of the sprite in degrees. Phaser uses a right-handed coordinate system, where 0 points to the right. * The value is automatically wrapped to be between 0 and 360. */ - public rotation : number; + public angle : number; /** * Get the animation frame number. */ @@ -2404,6 +3589,19 @@ module Phaser { * Clean up memory. */ public destroy(): void; + /** + * Handy for "killing" game objects. + * Default behavior is to flag them as nonexistent AND dead. + * However, if you want the "corpse" to remain in the game, + * like to animate an effect or whatever, you should override this, + * setting only alive to false, and leaving exists true. + */ + public kill(): void; + /** + * Handy for bringing game objects "back to life". Just sets alive and exists back to true. + * In practice, this is most often called by Object.reset(). + */ + public revive(): void; } } /** @@ -3025,312 +4223,927 @@ module Phaser { } } /** -* Phaser - Vec2Utils -* -* A collection of methods useful for manipulating and performing operations on 2D vectors. +* Phaser - Particle * +* This is a simple particle class that extends a Sprite to have a slightly more +* specialised behaviour. It is used exclusively by the Emitter class and can be extended as required. */ module Phaser { - class Vec2Utils { + class Particle extends Sprite { /** - * 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. + * Instantiate a new particle. Like Sprite, all meaningful creation + * happens during loadGraphic() or makeGraphic() or whatever. */ - static add(a: Vec2, b: Vec2, out?: Vec2): Vec2; + constructor(game: Game); /** - * 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. + * How long this particle lives before it disappears. + * NOTE: this is a maximum, not a minimum; the object + * could get recycled before its lifespan is up. */ - static subtract(a: Vec2, b: Vec2, out?: Vec2): Vec2; + public lifespan: number; /** - * 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. + * Determines how quickly the particles come to rest on the ground. + * Only used if the particle has gravity-like acceleration applied. + * @default 500 */ - static multiply(a: Vec2, b: Vec2, out?: Vec2): Vec2; + public friction: number; /** - * 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. + * 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. */ - static divide(a: Vec2, b: Vec2, out?: Vec2): Vec2; + public update(): void; /** - * 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. + * Triggered whenever this object is launched by a Emitter. + * You can override this to add custom behavior like a sound or AI or something. */ - static scale(a: Vec2, s: number, out?: Vec2): Vec2; - /** - * 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. - */ - static perp(a: Vec2, out?: Vec2): Vec2; - /** - * 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} - */ - static equals(a: Vec2, b: Vec2): bool; - /** - * - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} epsilon - * @return {Boolean} - */ - static epsilonEquals(a: Vec2, b: Vec2, epsilon: number): bool; - /** - * 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} - */ - static distance(a: Vec2, b: Vec2): number; - /** - * Get the distance squared between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @return {Number} - */ - static distanceSq(a: Vec2, b: Vec2): number; - /** - * Project two 2D vectors onto another vector. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @param {Vec2} b Reference to a source Vec2 object. - * @param {Vec2} out The output Vec2 that is the result of the operation. - * @return {Vec2} A Vec2. - */ - static project(a: Vec2, b: Vec2, out?: Vec2): Vec2; - /** - * 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. - */ - static projectUnit(a: Vec2, b: Vec2, out?: Vec2): Vec2; - /** - * 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. - */ - static normalRightHand(a: Vec2, out?: Vec2): Vec2; - /** - * 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. - */ - static normalize(a: Vec2, out?: Vec2): Vec2; - /** - * 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} - */ - static dot(a: Vec2, b: Vec2): number; - /** - * 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} - */ - static cross(a: Vec2, b: Vec2): number; - /** - * 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} - */ - static angle(a: Vec2, b: Vec2): number; - /** - * 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} - */ - static angleSq(a: Vec2, b: Vec2): number; - /** - * 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. - */ - static rotate(a: Vec2, b: Vec2, theta: number, out?: Vec2): Vec2; - /** - * 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. - */ - static clone(a: Vec2, out?: Vec2): Vec2; + public onEmit(): void; } } /** -* Phaser - Physics - IPhysicsShape -*/ -module Phaser.Physics { - interface IPhysicsShape { - game: Game; - world: PhysicsManager; - sprite: Sprite; - physics: Components.Physics; - position: Vec2; - oldPosition: Vec2; - offset: Vec2; - bounds: Rectangle; - setSize(width: number, height: number); - preUpdate(); - update(); - render(context: CanvasRenderingContext2D); - hullX; - hullY; - hullWidth; - hullHeight; - deltaX; - deltaY; - deltaXAbs; - deltaYAbs; - } -} -/** -* Phaser - PhysicsManager +* Phaser - Emitter * -* Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding -* all of the physics objects in the world. +* 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. */ -module Phaser.Physics { - class PhysicsManager { - constructor(game: Game, width: number, height: number); +module Phaser { + class Emitter extends Group { /** - * Local private reference to Game. + * Creates a new Emitter object at a specific position. + * Does NOT automatically generate or attach particles! + * + * @param x {number} The X position of the emitter. + * @param y {number} The Y position of the emitter. + * @param [size] {number} Specifies a maximum capacity for this emitter. + */ + constructor(game: Game, x?: number, y?: number, size?: number); + /** + * The X position of the top left corner of the emitter in world space. + */ + public x: number; + /** + * The Y position of the top left corner of emitter in world space. + */ + public y: number; + /** + * The width of the emitter. Particles can be randomly generated from anywhere within this box. + */ + public width: number; + /** + * The height of the emitter. Particles can be randomly generated from anywhere within this box. + */ + public height: number; + /** + * + */ + public alive: bool; + /** + * The minimum possible velocity of a particle. + * The default value is (-100,-100). + */ + public minParticleSpeed: Vec2; + /** + * The maximum possible velocity of a particle. + * The default value is (100,100). + */ + public maxParticleSpeed: Vec2; + /** + * The X and Y drag component of particles launched from the emitter. + */ + public particleDrag: Vec2; + /** + * The minimum possible angular velocity of a particle. The default value is -360. + * NOTE: rotating particles are more expensive to draw than non-rotating ones! + */ + public minRotation: number; + /** + * The maximum possible angular velocity of a particle. The default value is 360. + * NOTE: rotating particles are more expensive to draw than non-rotating ones! + */ + public maxRotation: number; + /** + * Sets the acceleration.y member of each particle to this value on launch. + */ + public gravity: number; + /** + * Determines whether the emitter is currently emitting particles. + * It is totally safe to directly toggle this. + */ + public on: bool; + /** + * How often a particle is emitted (if emitter is started with Explode == false). + */ + public frequency: number; + /** + * How long each particle lives once it is emitted. + * Set lifespan to 'zero' for particles to live forever. + */ + public lifespan: number; + /** + * How much each particle should bounce. 1 = full bounce, 0 = no bounce. + */ + public bounce: number; + /** + * Set your own particle class type here. + * Default is Particle. + */ + public particleClass; + /** + * Internal helper for deciding how many particles to launch. + */ + private _quantity; + /** + * Internal helper for the style of particle emission (all at once, or one at a time). + */ + private _explode; + /** + * Internal helper for deciding when to launch particles or kill them. + */ + private _timer; + /** + * Internal counter for figuring out how many particles to launch. + */ + private _counter; + /** + * Internal point object, handy for reusing for memory mgmt purposes. + */ + private _point; + /** + * Clean up memory. + */ + public destroy(): void; + /** + * This function generates a new array of particle sprites to attach to the emitter. + * + * @param graphics If you opted to not pre-configure an array of Sprite objects, you can simply pass in a particle image or sprite sheet. + * @param quantity {number} The number of particles to generate when using the "create from image" option. + * @param multiple {boolean} Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!). + * @param collide {number} Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box. + * + * @return This Emitter instance (nice for chaining stuff together, if you're into that). + */ + public makeParticles(graphics, quantity?: number, multiple?: bool, collide?: number): Emitter; + /** + * Called automatically by the game loop, decides when to launch particles and when to "die". */ - public game: Game; - private _objects; - private _drag; - private _delta; - private _velocityDelta; - private _length; - private _distance; - private _tangent; - public bounds: Rectangle; - public gravity: Vec2; - public drag: Vec2; - public bounce: Vec2; - public friction: Vec2; - public add(shape: IPhysicsShape): IPhysicsShape; - public remove(shape: IPhysicsShape): void; public update(): void; - public render(): void; - private updateMotion(shape); /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * Call this function to turn off all the particles and the emitter. + */ + public kill(): void; + /** + * Handy for bringing game objects "back to life". Just sets alive and exists back to true. + * In practice, this is most often called by Object.reset(). + */ + public revive(): void; + /** + * Call this function to start emitting particles. * - * @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. + * @param explode {boolean} Whether the particles should all burst out at once. + * @param lifespan {number} How long each particle lives once emitted. 0 = forever. + * @param frequency {number} Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds. + * @param quantity {number} How many particles to launch. 0 = "all of the particles". + */ + public start(explode?: bool, lifespan?: number, frequency?: number, quantity?: number): void; + /** + * This function can be used both internally and externally to emit the next particle. + */ + public emitParticle(): void; + /** + * A more compact way of setting the width and height of the emitter. * - * @return {number} The altered Velocity value. + * @param width {number} The desired width of the emitter (particles are spawned randomly within these dimensions). + * @param height {number} The desired height of the emitter. */ - public computeVelocity(velocity: number, gravity?: number, acceleration?: number, drag?: number, max?: number): number; - private collideShapes(shapeA, shapeB); + public setSize(width: number, height: number): void; /** - * 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. + * A more compact way of setting the X velocity range of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. */ - public NEWseparate(object1, object2): bool; - private checkHullIntersection(shape1, shape2); + public setXSpeed(min?: number, max?: number): void; /** - * 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. + * A more compact way of setting the Y velocity range of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. */ - public separateSpriteToSpriteX(object1: Sprite, object2: Sprite): bool; + public setYSpeed(min?: number, max?: number): void; /** - * 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. + * A more compact way of setting the angular velocity constraints of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. */ - public separateSpriteToSpriteY(object1: Sprite, object2: Sprite): bool; - private separate(shapeA, shapeB, distance, tangent); - private collideWorld(shape); - private separateX(shapeA, shapeB, distance, tangent); - private separateY(shapeA, shapeB, distance, tangent); - private separateXWall(shapeA, distance, tangent); - private separateYWall(shapeA, distance, tangent); - private OLDseparate(shape, distance, tangent); + public setRotation(min?: number, max?: number): void; + /** + * Change the emitter's midpoint to match the midpoint of a Object. + * + * @param Object {object} The Object that you want to sync up with. + */ + public at(object: Sprite): void; } } /** -* Phaser - Physics - AABB +* Phaser - ScrollRegion +* +* Creates a scrolling region within a ScrollZone. +* It is scrolled via the scrollSpeed.x/y properties. */ -module Phaser.Physics { - class AABB implements IPhysicsShape { - constructor(game: Game, sprite: Sprite, x: number, y: number, width: number, height: number); - public game: Game; - public world: PhysicsManager; - public sprite: Sprite; - public physics: Components.Physics; - public position: Vec2; - public oldPosition: Vec2; - public offset: Vec2; - public scale: Vec2; - public bounds: Rectangle; - public preUpdate(): void; +module Phaser { + class ScrollRegion { + /** + * 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. + */ + 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; + /** + * Will this region be rendered? (default to true) + * @type {boolean} + */ + public visible: bool; + /** + * Region scrolling speed. + * @type {Vec2} + */ + public scrollSpeed: Vec2; + /** + * Update region scrolling with tick time. + * @param delta {number} Elapsed time since last update. + */ + public update(delta: number): void; + /** + * Render this region to specific context. + * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. + * @param texture {object} The texture to be rendered. + * @param dx {number} X position in world coordinate. + * @param dy {number} Y position in world coordinate. + * @param width {number} Width of this region to be rendered. + * @param height {number} Height of this region to be rendered. + */ + public render(context: CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number): void; + /** + * Crop part of the texture and render it to the given context. + * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. + * @param texture {object} Texture to be rendered. + * @param srcX {number} Target region top-left x coordinate in the texture. + * @param srcX {number} Target region top-left y coordinate in the texture. + * @param srcW {number} Target region width in the texture. + * @param srcH {number} Target region height in the texture. + * @param destX {number} Render region top-left x coordinate in the context. + * @param destX {number} Render region top-left y coordinate in the context. + * @param destW {number} Target region width in the context. + * @param destH {number} Target region height in the context. + * @param offsetX {number} X offset to the context. + * @param offsetY {number} Y offset to the context. + */ + private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY); + } +} +/** +* Phaser - ScrollZone +* +* Creates a scrolling region of the given width and height from an image in the cache. +* The ScrollZone can be positioned anywhere in-world like a normal game object, re-act to physics, collision, etc. +* The image within it is scrolled via ScrollRegions and their scrollSpeed.x/y properties. +* If you create a scroll zone larger than the given source image it will create a DynamicTexture and fill it with a pattern of the source image. +*/ +module Phaser { + class ScrollZone extends Sprite { + /** + * 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. + */ + constructor(game: Game, key: string, x?: number, y?: number, width?: number, height?: number); + /** + * Current region this zone is scrolling. + * @type {ScrollRegion} + */ + public currentRegion: ScrollRegion; + /** + * Array contains all added regions. + * @type {ScrollRegion[]} + */ + public regions: ScrollRegion[]; + /** + * Add a new region to this zone. + * @param x {number} X position of the new region. + * @param y {number} Y position of the new region. + * @param width {number} Width of the new region. + * @param height {number} Height of the new region. + * @param [speedX] {number} x-axis scrolling speed. + * @param [speedY] {number} y-axis scrolling speed. + * @return {ScrollRegion} The newly added region. + */ + public addRegion(x: number, y: number, width: number, height: number, speedX?: number, speedY?: number): ScrollRegion; + /** + * Set scrolling speed of current region. + * @param x {number} X speed of current region. + * @param y {number} Y speed of current region. + */ + public setSpeed(x: number, y: number): ScrollZone; + /** + * Update regions. + */ public update(): void; - public setSize(width: number, height: number): void; - public render(context: CanvasRenderingContext2D): void; - public hullWidth : number; - public hullHeight : number; - public hullX : number; - public hullY : number; - public deltaXAbs : number; - public deltaYAbs : number; - public deltaX : number; - public deltaY : number; + /** + * Create repeating texture with _texture, and store it into the _dynamicTexture. + * Used to create texture when texture image is small than size of the zone. + */ + private createRepeatingTexture(regionWidth, regionHeight); + } +} +/** +* Phaser - TilemapLayer +* +* A Tilemap Layer. Tiled format maps can have multiple overlapping layers. +*/ +module Phaser { + class TilemapLayer { + /** + * 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. + */ + constructor(game: Game, parent: Tilemap, key: string, mapFormat: number, name: string, tileWidth: number, tileHeight: number); + /** + * Local private reference to game. + */ + private _game; + /** + * The tilemap that contains this layer. + * @type {Tilemap} + */ + private _parent; + /** + * Tileset of this layer. + */ + private _texture; + private _tileOffsets; + private _startX; + private _startY; + private _maxX; + private _maxY; + private _tx; + private _ty; + private _dx; + private _dy; + private _oldCameraX; + private _oldCameraY; + private _columnData; + private _tempTileX; + private _tempTileY; + private _tempTileW; + private _tempTileH; + private _tempTileBlock; + private _tempBlockResults; + /** + * Name of this layer, so you can get this layer by its name. + * @type {string} + */ + public name: string; + /** + * A reference to the Canvas this GameObject will render to + * @type {HTMLCanvasElement} + */ + public canvas: HTMLCanvasElement; + /** + * A reference to the Canvas Context2D this GameObject will render to + * @type {CanvasRenderingContext2D} + */ + public context: CanvasRenderingContext2D; + /** + * Opacity of this layer. + * @type {number} + */ + public alpha: number; + /** + * Controls whether update() and draw() are automatically called. + * @type {boolean} + */ + public exists: bool; + /** + * Controls whether draw() are automatically called. + * @type {boolean} + */ + public visible: bool; + /** + * @type {string} + */ + public orientation: string; + /** + * Properties of this map layer. (normally set by map editors) + */ + public properties: {}; + /** + * Map data in a 2d array, its element is a index number for that tile. + * @type {number[][]} + */ + public mapData; + /** + * Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. + */ + public mapFormat: number; + /** + * It's width and height are in tiles instead of pixels. + * @type {Rectangle} + */ + public boundsInTiles: Rectangle; + /** + * Width of each tile. + * @type {number} + */ + public tileWidth: number; + /** + * Height of a single tile. + * @type {number} + */ + public tileHeight: number; + /** + * How many tiles in each row. + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + public widthInTiles: number; + /** + * How many tiles in each column. + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + public heightInTiles: number; + /** + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + public widthInPixels: number; + /** + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + public heightInPixels: number; + /** + * Distance between REAL tiles to the tileset texture bound. + * @type {number} + */ + public tileMargin: number; + /** + * Distance between every 2 neighbor tile in the tileset texture. + * @type {number} + */ + public tileSpacing: number; + /** + * Set a specific tile with its x and y in tiles. + * @param x {number} X position of this tile. + * @param y {number} Y position of this tile. + * @param index {number} The index of this tile type in the core map data. + */ + public putTile(x: number, y: number, index: number): void; + /** + * Swap tiles with 2 kinds of indexes. + * @param tileA {number} First tile index. + * @param tileB {number} Second tile index. + * @param [x] {number} specify a rectangle of tiles to operate. The x position in tiles of rectangle's left-top corner. + * @param [y] {number} specify a rectangle of tiles to operate. The y position in tiles of rectangle's left-top corner. + * @param [width] {number} specify a rectangle of tiles to operate. The width in tiles. + * @param [height] {number} specify a rectangle of tiles to operate. The height in tiles. + */ + public swapTile(tileA: number, tileB: number, x?: number, y?: number, width?: number, height?: number): void; + /** + * Fill a tile block with a specific tile index. + * @param index {number} Index of tiles you want to fill with. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + public fillTile(index: number, x?: number, y?: number, width?: number, height?: number): void; + /** + * Set random tiles to a specific tile block. + * @param tiles {number[]} Tiles with indexes in this array will be randomly set to the given block. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + public randomiseTiles(tiles: number[], x?: number, y?: number, width?: number, height?: number): void; + /** + * Replace one kind of tiles to another kind. + * @param tileA {number} Index of tiles you want to replace. + * @param tileB {number} Index of tiles you want to set. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + public replaceTile(tileA: number, tileB: number, x?: number, y?: number, width?: number, height?: number): void; + /** + * Get a tile block with specific position and size.(both are in tiles) + * @param x {number} X position of block's left-top corner. + * @param y {number} Y position of block's left-top corner. + * @param width {number} Width of block. + * @param height {number} Height of block. + */ + public getTileBlock(x: number, y: number, width: number, height: number): any[]; + /** + * Get a tile with specific position (in world coordinate). (thus you give a position of a point which is within the tile) + * @param x {number} X position of the point in target tile. + * @param x {number} Y position of the point in target tile. + */ + public getTileFromWorldXY(x: number, y: number): number; + /** + * Get tiles overlaps the given object. + * @param object {GameObject} Tiles you want to get that overlaps this. + * @return {array} Array with tiles informations. (Each contains x, y and the tile.) + */ + public getTileOverlaps(object: Sprite); + /** + * Get a tile block with its position and size. (This method does not return, it'll set result to _tempTileBlock) + * @param x {number} X position of block's left-top corner. + * @param y {number} Y position of block's left-top corner. + * @param width {number} Width of block. + * @param height {number} Height of block. + * @param collisionOnly {boolean} Whethor or not ONLY return tiles which will collide (its allowCollisions value is not Collision.NONE). + */ + private getTempBlock(x, y, width, height, collisionOnly?); + /** + * Get the tile index of specific position (in tiles). + * @param x {number} X position of the tile. + * @param y {number} Y position of the tile. + * @return {number} Index of the tile at that position. Return null if there isn't a tile there. + */ + public getTileIndex(x: number, y: number): number; + /** + * Add a column of tiles into the layer. + * @param column {string[]/number[]} An array of tile indexes to be added. + */ + public addColumn(column): void; + /** + * Update boundsInTiles with widthInTiles and heightInTiles. + */ + public updateBounds(): void; + /** + * Parse tile offsets from map data. + * @return {number} length of _tileOffsets array. + */ + public parseTileOffsets(): number; + public renderDebugInfo(x: number, y: number, color?: string): void; + /** + * Render this layer to a specific camera with offset to camera. + * @param camera {Camera} The camera the layer is going to be rendered. + * @param dx {number} X offset to the camera. + * @param dy {number} Y offset to the camera. + * @return {boolean} Return false if layer is invisible or has a too low opacity(will stop rendering), return true if succeed. + */ + public render(camera: Camera, dx, dy): bool; + } +} +/** +* Phaser - Tile +* +* A Tile is a single representation of a tile within a Tilemap +*/ +module Phaser { + class Tile { + /** + * Tile constructor + * Create a new Tile. + * + * @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. + */ + constructor(game: Game, tilemap: Tilemap, index: number, width: number, height: number); + /** + * Local private reference to game. + */ + private _game; + /** + * You can give this Tile a friendly name to help with debugging. Never used internally. + * @type {string} + */ + public name: string; + /** + * The virtual mass of the tile. + * @type {number} + */ + public mass: number; + /** + * Tile width. + * @type {number} + */ + public width: number; + /** + * Tile height. + * @type {number} + */ + public height: number; + /** + * Bit field of flags (use with UP, DOWN, LEFT, RIGHT, etc) indicating collision directions. + * @type {number} + */ + public allowCollisions: number; + /** + * Indicating collide with any object on the left. + * @type {boolean} + */ + public collideLeft: bool; + /** + * Indicating collide with any object on the right. + * @type {boolean} + */ + public collideRight: bool; + /** + * Indicating collide with any object on the top. + * @type {boolean} + */ + public collideUp: bool; + /** + * Indicating collide with any object on the bottom. + * @type {boolean} + */ + public collideDown: bool; + /** + * Enable separation at x-axis. + * @type {boolean} + */ + public separateX: bool; + /** + * Enable separation at y-axis. + * @type {boolean} + */ + public separateY: bool; + /** + * A reference to the tilemap this tile object belongs to. + * @type {Tilemap} + */ + public tilemap: Tilemap; + /** + * The index of this tile type in the core map data. + * For example, if your map only has 16 kinds of tiles in it, + * this number is usually between 0 and 15. + * @type {number} + */ + public index: number; + /** + * Clean up memory. + */ + public destroy(): void; + /** + * Set collision configs. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + public setCollision(collision: number, resetCollisions: bool, separateX: bool, separateY: bool): void; + /** + * Reset collision status flags. + */ + public resetCollision(): void; + /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + public toString(): string; + } +} +/** +* Phaser - Tilemap +* +* This GameObject allows for the display of a tilemap within the game world. Tile maps consist of an image, tile data and a size. +* Internally it creates a TilemapLayer for each layer in the tilemap. +*/ +module Phaser { + class Tilemap { + /** + * 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. + */ + constructor(game: Game, key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number); + private _tempCollisionData; + /** + * Reference to the main game object + */ + public game: Game; + /** + * The type of game object. + */ + public type: number; + /** + * Controls if both update and render are called by the core game loop. + */ + public exists: bool; + /** + * Controls if update() is automatically called by the core game loop. + */ + public active: bool; + /** + * Controls if this Sprite is rendered or skipped during the core game loop. + */ + public visible: bool; + /** + * + */ + public alive: bool; + /** + * Tilemap data format enum: CSV. + * @type {number} + */ + static FORMAT_CSV: number; + /** + * Tilemap data format enum: Tiled JSON. + * @type {number} + */ + static FORMAT_TILED_JSON: number; + /** + * Array contains tile objects of this map. + * @type {Tile[]} + */ + public tiles: Tile[]; + /** + * Array contains tilemap layer objects of this map. + * @type {TilemapLayer[]} + */ + public layers: TilemapLayer[]; + /** + * Current tilemap layer. + * @type {TilemapLayer} + */ + public currentLayer: TilemapLayer; + /** + * The tilemap layer for collision. + * @type {TilemapLayer} + */ + public collisionLayer: TilemapLayer; + /** + * Tilemap collision callback. + * @type {function} + */ + public collisionCallback; + /** + * Context for the collision callback called with. + */ + public collisionCallbackContext; + /** + * Format of this tilemap data. Available values: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. + * @type {number} + */ + public mapFormat: number; + /** + * An Array of Cameras to which this GameObject won't render + * @type {Array} + */ + public cameraBlacklist: number[]; + /** + * Inherited update method. + */ + public update(): void; + /** + * Render this tilemap to a specific camera with specific offset. + * @param camera {Camera} The camera this tilemap will be rendered to. + * @param cameraOffsetX {number} X offset of the camera. + * @param cameraOffsetY {number} Y offset of the camera. + */ + public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void; + /** + * Parset csv map data and generate tiles. + * @param data {string} CSV map data. + * @param key {string} Asset key for tileset image. + * @param tileWidth {number} Width of its tile. + * @param tileHeight {number} Height of its tile. + */ + private parseCSV(data, key, tileWidth, tileHeight); + /** + * Parset JSON map data and generate tiles. + * @param data {string} JSON map data. + * @param key {string} Asset key for tileset image. + */ + private parseTiledJSON(data, key); + /** + * Create tiles of given quantity. + * @param qty {number} Quentity of tiles to be generated. + */ + private generateTiles(qty); + public widthInPixels : number; + public heightInPixels : number; + /** + * Set callback to be called when this tilemap collides. + * @param context {object} Callback will be called with this context. + * @param callback {function} Callback function. + */ + public setCollisionCallback(context, callback): void; + /** + * Set collision configs of tiles in a range index. + * @param start {number} First index of tiles. + * @param end {number} Last index of tiles. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + public setCollisionRange(start: number, end: number, collision?: number, resetCollisions?: bool, separateX?: bool, separateY?: bool): void; + /** + * Set collision configs of tiles with given index. + * @param values {number[]} Index array which contains all tile indexes. The tiles with those indexes will be setup with rest parameters. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + public setCollisionByIndex(values: number[], collision?: number, resetCollisions?: bool, separateX?: bool, separateY?: bool): void; + /** + * Get the tile by its index. + * @param value {number} Index of the tile you want to get. + * @return {Tile} The tile with given index. + */ + public getTileByIndex(value: number): Tile; + /** + * Get the tile located at specific position and layer. + * @param x {number} X position of this tile located. + * @param y {number} Y position of this tile located. + * @param [layer] {number} layer of this tile located. + * @return {Tile} The tile with specific properties. + */ + public getTile(x: number, y: number, layer?: number): Tile; + /** + * Get the tile located at specific position (in world coordinate) and layer. (thus you give a position of a point which is within the tile) + * @param x {number} X position of the point in target tile. + * @param x {number} Y position of the point in target tile. + * @param [layer] {number} layer of this tile located. + * @return {Tile} The tile with specific properties. + */ + public getTileFromWorldXY(x: number, y: number, layer?: number): Tile; + public getTileFromInputXY(layer?: number): Tile; + /** + * Get tiles overlaps the given object. + * @param object {GameObject} Tiles you want to get that overlaps this. + * @return {array} Array with tiles informations. (Each contains x, y and the tile.) + */ + public getTileOverlaps(object: Sprite); + /** + * Check whether this tilemap collides with the given game object or group of objects. + * @param objectOrGroup {function} Target object of group you want to check. + * @param callback {function} This is called if objectOrGroup collides the tilemap. + * @param context {object} Callback will be called with this context. + * @return {boolean} Return true if this collides with given object, otherwise return false. + */ + public collide(objectOrGroup?, callback?, context?): void; + /** + * Check whether this tilemap collides with the given game object. + * @param object {GameObject} Target object you want to check. + * @return {boolean} Return true if this collides with given object, otherwise return false. + */ + public collideGameObject(object: Sprite): bool; + /** + * Set a tile to a specific layer. + * @param x {number} X position of this tile. + * @param y {number} Y position of this tile. + * @param index {number} The index of this tile type in the core map data. + * @param [layer] {number} which layer you want to set the tile to. + */ + public putTile(x: number, y: number, index: number, layer?: number): void; } } /** @@ -3368,10 +5181,11 @@ module Phaser { * * @param x {number} X position of the new sprite. * @param y {number} Y position of the new sprite. - * @param key {string} Optional, key for the sprite sheet you want it to use. + * @param [key] {string} The image key as defined in the Game.Cache to use as the texture for this sprite + * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) * @returns {Sprite} The newly created sprite object. */ - public sprite(x: number, y: number, key?: string): Sprite; + public sprite(x: number, y: number, key?: string, bodyType?: number): Sprite; /** * Create a new DynamicTexture with specific size. * @@ -3388,15 +5202,20 @@ module Phaser { */ public group(maxSize?: number): Group; /** - * Create a new Sprite with specific position and sprite sheet key. + * Create a new Particle. * - * @param x {number} X position of the new sprite. - * @param y {number} Y position of the new sprite. - * @param key {string} Optional, key for the sprite sheet you want it to use. - * @returns {Sprite} The newly created sprite object. - * WILL NEED TO TRACK A SPRITE + * @return {Particle} The newly created particle object. */ - public physicsAABB(x: number, y: number, width: number, height: number): Physics.AABB; + public particle(): Particle; + /** + * Create a new Emitter. + * + * @param x {number} Optional, x position of the emitter. + * @param y {number} Optional, y position of the emitter. + * @param size {number} Optional, size of this emitter. + * @return {Emitter} The newly created emitter object. + */ + public emitter(x?: number, y?: number, size?: number): Emitter; /** * Create a new ScrollZone object with image key, position and size. * @@ -3409,6 +5228,18 @@ module Phaser { */ public scrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone; /** + * Create a new Tilemap. + * + * @param key {string} Key for tileset image. + * @param mapData {string} Data of this tilemap. + * @param format {number} Format of map data. (Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON) + * @param [resizeWorld] {boolean} resize the world to make same as tilemap? + * @param [tileWidth] {number} width of each tile. + * @param [tileHeight] {number} height of each tile. + * @return {Tilemap} The newly created tilemap object. + */ + public tilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap; + /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -3424,6 +5255,14 @@ module Phaser { */ public existingSprite(sprite: Sprite): 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 + */ + public existingEmitter(emitter: Emitter): Emitter; + /** * Add an existing ScrollZone to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -3432,6 +5271,14 @@ module Phaser { */ public existingScrollZone(scrollZone: ScrollZone): ScrollZone; /** + * Add an existing Tilemap to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param tilemap The Tilemap to add to the Game World + * @return {Phaser.Tilemap} The Tilemap object + */ + public existingTilemap(tilemap: Tilemap): Tilemap; + /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -3441,602 +5288,6 @@ module Phaser { public existingTween(tween: Tween): Tween; } } -module Phaser { - /** - * Constants used to define game object types (faster than doing typeof object checks in core loops) - */ - class Types { - static RENDERER_AUTO_DETECT: number; - static RENDERER_HEADLESS: number; - static RENDERER_CANVAS: number; - static RENDERER_WEBGL: number; - static GROUP: number; - static SPRITE: number; - static GEOMSPRITE: number; - static PARTICLE: number; - static EMITTER: number; - static TILEMAP: number; - static SCROLLZONE: number; - static GEOM_POINT: number; - static GEOM_CIRCLE: number; - static GEOM_RECTANGLE: number; - static GEOM_LINE: number; - static GEOM_POLYGON: number; - /** - * Flag used to allow GameObjects to collide on their left side - * @type {number} - */ - static LEFT: number; - /** - * Flag used to allow GameObjects to collide on their right side - * @type {number} - */ - static RIGHT: number; - /** - * Flag used to allow GameObjects to collide on their top side - * @type {number} - */ - static UP: number; - /** - * Flag used to allow GameObjects to collide on their bottom side - * @type {number} - */ - static DOWN: number; - /** - * Flag used with GameObjects to disable collision - * @type {number} - */ - static NONE: number; - /** - * Flag used to allow GameObjects to collide with a ceiling - * @type {number} - */ - static CEILING: number; - /** - * Flag used to allow GameObjects to collide with a floor - * @type {number} - */ - static FLOOR: number; - /** - * Flag used to allow GameObjects to collide with a wall (same as LEFT+RIGHT) - * @type {number} - */ - static WALL: number; - /** - * Flag used to allow GameObjects to collide on any face - * @type {number} - */ - static ANY: number; - } -} -/** -* Phaser - Group -* -* This class is used for organising, updating and sorting game objects. -*/ -module Phaser { - class Group { - constructor(game: Game, maxSize?: number); - /** - * Internal tracker for the maximum capacity of the group. - * Default is 0, or no max capacity. - */ - private _maxSize; - /** - * Internal helper variable for recycling objects a la Emitter. - */ - private _marker; - /** - * Helper for sort. - */ - private _sortIndex; - /** - * Helper for sort. - */ - private _sortOrder; - /** - * Temp vars to help avoid gc spikes - */ - private _member; - private _length; - private _i; - private _prevAlpha; - private _count; - /** - * Reference to the main game object - */ - public game: Game; - /** - * The type of game object. - */ - public type: number; - /** - * If this Group exists or not. Can be set to false to skip certain loop checks. - */ - public exists: bool; - /** - * Controls if this Group (and all of its contents) are rendered or skipped during the core game loop. - */ - public visible: bool; - /** - * Use with sort() to sort in ascending order. - */ - static ASCENDING: number; - /** - * Use with sort() to sort in descending order. - */ - static DESCENDING: number; - /** - * Array of all the objects that exist in this group. - */ - public members; - /** - * The number of entries in the members array. - * For performance and safety you should check this variable - * instead of members.length unless you really know what you're doing! - */ - public length: number; - /** - * 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. - * If this value is set it will call a canvas context save and restore before and after the render pass. - * Set to null to disable. - */ - public globalCompositeOperation: string; - /** - * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. - * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. - * Set to 0 to disable. - */ - public alpha: number; - /** - * An Array of Cameras to which this Group, or any of its children, won't render - * @type {Array} - */ - public cameraBlacklist: number[]; - /** - * Override this function to handle any deleting or "shutdown" type operations you might need, - * such as removing traditional Flash children like Basic objects. - */ - public destroy(): void; - /** - * Calls update on all members of this Group who have a status of active=true and exists=true - * You can also call Object.update directly, which will bypass the active/exists check. - */ - public update(forceUpdate?: bool): void; - /** - * 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(renderer: IRenderer, camera: Camera): void; - /** - * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. - */ - /** - * @private - */ - public maxSize : number; - /** - * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. - * Group will try to replace a null member of the array first. - * Failing that, Group will add it to the end of the member array, - * assuming there is room for it, and doubling the size of the array if necessary. - * - *

WARNING: If the group has a maxSize that has already been met, - * the object will NOT be added to the group!

- * - * @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): any; - /** - * Recycling is designed to help you reuse game objects without always re-allocating or "newing" them. - * - *

If you specified a maximum size for this group (like in Emitter), - * then recycle will employ what we're calling "rotating" recycling. - * Recycle() will first check to see if the group is at capacity yet. - * If group is not yet at capacity, recycle() returns a new object. - * If the group IS at capacity, then recycle() just returns the next object in line.

- * - *

If you did NOT specify a maximum size for this group, - * then recycle() will employ what we're calling "grow-style" recycling. - * Recycle() will return either the first object with exists == false, - * or, finding none, add a new object to the array, - * doubling the size of the array if necessary.

- * - *

WARNING: If this function needs to create a new object, - * and no object class was provided, it will return null - * instead of a valid object!

- * - * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! - * - * @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?); - /** - * Removes an object from the group. - * - * @param {Basic} object The Basic you want to remove. - * @param {boolean} splice Whether the object should be cut from the array entirely or not. - * - * @return {Basic} The removed object. - */ - public remove(object, splice?: bool); - /** - * Replaces an existing Basic with a new one. - * - * @param {Basic} oldObject The object you want to replace. - * @param {Basic} newObject The new object you want to use instead. - * - * @return {Basic} The new object. - */ - public replace(oldObject, newObject); - /** - * Call this function to sort the group according to a particular value and order. - * For example, to sort game objects for Zelda-style overlaps you might call - * myGroup.sort("y",Group.ASCENDING) at the bottom of your - * State.update() override. To sort all existing objects after - * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). - * - * @param {string} index The string name of the member variable you want to sort on. Default value is "y". - * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. - */ - public sort(index?: string, order?: number): void; - /** - * Go through and set the specified variable to the specified value on all members of the group. - * - * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". - * @param {Object} Value The value you want to assign to that variable. - * @param {boolean} Recurse Default value is true, meaning if setAll() encounters a member that is a group, it will call setAll() on that group rather than modifying its variable. - */ - public setAll(variableName: string, value: Object, recurse?: bool): void; - /** - * Go through and call the specified function on all members of the group. - * Currently only works on functions that have no required parameters. - * - * @param {string} FunctionName The string representation of the function you want to call on each object, for example "kill()" or "init()". - * @param {boolean} Recurse Default value is true, meaning if callAll() encounters a member that is a group, it will call callAll() on that group rather than calling the group's function. - */ - public callAll(functionName: string, recurse?: bool): void; - /** - * @param {function} callback - * @param {boolean} recursive - */ - public forEach(callback, recursive?: bool): void; - /** - * @param {any} context - * @param {function} callback - * @param {boolean} recursive - */ - public forEachAlive(context, callback, recursive?: bool): void; - /** - * Call this function to retrieve the first object with exists == false in the group. - * This is handy for recycling in general, e.g. respawning enemies. - * - * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. - * - * @return {any} A Basic currently flagged as not existing. - */ - public getFirstAvailable(objectClass?); - /** - * Call this function to retrieve the first index set to 'null'. - * Returns -1 if no index stores a null object. - * - * @return {number} An int indicating the first null slot in the group. - */ - public getFirstNull(): number; - /** - * Call this function to retrieve the first object with exists == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as existing. - */ - public getFirstExtant(); - /** - * Call this function to retrieve the first object with dead == false in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as not dead. - */ - public getFirstAlive(); - /** - * Call this function to retrieve the first object with dead == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as dead. - */ - public getFirstDead(); - /** - * Call this function to find out how many members of the group are not dead. - * - * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. - */ - public countLiving(): number; - /** - * Call this function to find out how many members of the group are dead. - * - * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. - */ - public countDead(): number; - /** - * Returns a member at random from the group. - * - * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} Length Optional restriction on the number of values you want to randomly select from. - * - * @return {Basic} A Basic from the members list. - */ - public getRandom(startIndex?: number, length?: number); - /** - * Remove all instances of Basic subclass (Basic, Block, etc) from the list. - * WARNING: does not destroy() or kill() any of these objects! - */ - public clear(): void; - /** - * Calls kill on the group's members and then on the group itself. - */ - public kill(): void; - /** - * Helper function for the sort process. - * - * @param {Basic} Obj1 The first object being sorted. - * @param {Basic} Obj2 The second object being sorted. - * - * @return {number} An integer value: -1 (Obj1 before Obj2), 0 (same), or 1 (Obj1 after Obj2). - */ - public sortHandler(obj1, obj2): number; - } -} -/** -* Phaser - SignalBinding -* -* An object that represents a binding between a Signal and a listener function. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -module Phaser { - class SignalBinding { - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number); - /** - * Handler function bound to the signal. - * @type Function - * @private - */ - private _listener; - /** - * If binding should be executed just once. - * @type boolean - * @private - */ - private _isOnce; - /** - * Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @memberOf SignalBinding.prototype - * @name context - * @type Object|undefined|null - */ - public context; - /** - * Reference to Signal object that listener is currently bound to. - * @type Signal - * @private - */ - private _signal; - /** - * Listener priority - * @type Number - */ - public priority: number; - /** - * If binding is active and should be executed. - * @type boolean - */ - public active: bool; - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - public params; - /** - * Call listener passing arbitrary parameters. - *

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

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

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

- * @type boolean - */ - public active: bool; - /** - * - * @method validateListener - * @param {Any} listener - * @param {Any} fnName - */ - public validateListener(listener, fnName): void; - /** - * @param {Function} listener - * @param {boolean} isOnce - * @param {Object} [listenerContext] - * @param {Number} [priority] - * @return {SignalBinding} - * @private - */ - private _registerListener(listener, isOnce, listenerContext, priority); - /** - * - * @method _addBinding - * @param {SignalBinding} binding - * @private - */ - private _addBinding(binding); - /** - * - * @method _indexOfListener - * @param {Function} listener - * @return {number} - * @private - */ - private _indexOfListener(listener, context); - /** - * Check if listener was attached to Signal. - * @param {Function} listener - * @param {Object} [context] - * @return {boolean} if Signal has the specified listener. - */ - public has(listener, context?: any): bool; - /** - * Add a listener to the signal. - * @param {Function} listener Signal handler function. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - * @return {SignalBinding} An Object representing the binding between the Signal and listener. - */ - public add(listener, listenerContext?: any, priority?: number): SignalBinding; - /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * @param {Function} listener Signal handler function. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - * @return {SignalBinding} An Object representing the binding between the Signal and listener. - */ - public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding; - /** - * Remove a single listener from the dispatch queue. - * @param {Function} listener Handler function that should be removed. - * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {Function} Listener handler function. - */ - public remove(listener, context?: any); - /** - * Remove all listeners from the Signal. - */ - public removeAll(): void; - /** - * @return {number} Number of listeners attached to the Signal. - */ - public getNumListeners(): number; - /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - *

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

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

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

- */ - public dispose(): void; - /** - * @return {string} String representation of the object. - */ - public toString(): string; - } -} /** * Phaser - Sound * @@ -4728,6 +5979,196 @@ module Phaser { } } /** +* Phaser - CircleUtils +* +* A collection of methods useful for manipulating and comparing Circle objects. +* +* TODO: +*/ +module Phaser { + class CircleUtils { + /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. + * @method clone + * @param {Circle} a - The Circle object. + * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} + **/ + static clone(a: Circle, out?: Circle): Circle; + /** + * Return true if the given x/y coordinates are within the Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method contains + * @param {Circle} a - The Circle object. + * @param {Number} The X value of the coordinate to test. + * @param {Number} The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static contains(a: Circle, x: number, y: number): bool; + /** + * Return true if the coordinates of the given Point object are within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method containsPoint + * @param {Circle} a - The Circle object. + * @param {Point} The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static containsPoint(a: Circle, point: Point): bool; + /** + * Return true if the given Circle is contained entirely within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. + * @method containsCircle + * @param {Circle} The Circle object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + static containsCircle(a: Circle, b: Circle): bool; + /** + * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) + * @method distanceBetween + * @param {Circle} a - The Circle object. + * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between this Point object and the destination Point object. + **/ + static distanceBetween(a: Circle, target: any, round?: bool): number; + /** + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + **/ + static equals(a: Circle, b: Circle): bool; + /** + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method intersects + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + **/ + static intersects(a: Circle, b: Circle): bool; + /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Circle} a - The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + **/ + static circumferencePoint(a: Circle, angle: number, asDegrees?: bool, out?: Point): Point; + static intersectsRectangle(c: Circle, r: Rectangle): bool; + } +} +/** +* Phaser - PhysicsManager +* +* Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding +* all of the physics objects in the world. +*/ +module Phaser.Physics { + class PhysicsManager { + constructor(game: Game, width: number, height: number); + /** + * Local private reference to Game. + */ + public game: Game; + /** + * Physics object pool + */ + public members: Group; + private _drag; + private _delta; + private _velocityDelta; + private _length; + private _distance; + private _tangent; + private _separatedX; + private _separatedY; + private _overlap; + private _maxOverlap; + private _obj1Velocity; + private _obj2Velocity; + private _obj1NewVelocity; + private _obj2NewVelocity; + private _average; + private _quadTree; + private _quadTreeResult; + public bounds: Rectangle; + public gravity: Vec2; + public drag: Vec2; + public bounce: Vec2; + public angularDrag: number; + /** + * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects + * @type {number} + */ + static OVERLAP_BIAS: number; + /** + * The overlap bias is used when calculating hull overlap before separation - change it if you have especially small or large GameObjects + * @type {number} + */ + static TILE_OVERLAP: bool; + /** + * @type {number} + */ + public worldDivisions: number; + public updateMotion(body: Body): void; + /** + * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. + * + * @param {number} Velocity Any component of velocity (e.g. 20). + * @param {number} Acceleration Rate at which the velocity is changing. + * @param {number} Drag Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. + * @param {number} Max An absolute value cap for the velocity. + * + * @return {number} The altered Velocity value. + */ + public computeVelocity(velocity: number, gravity?: number, acceleration?: number, drag?: number, max?: number): number; + /** + * The core Collision separation method. + * @param body1 The first Physics.Body to separate + * @param body2 The second Physics.Body to separate + * @returns {boolean} Returns true if the bodies were separated, otherwise false. + */ + public separate(body1: Body, body2: Body): bool; + private checkHullIntersection(body1, body2); + /** + * 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. + */ + public separateBodyX(body1: Body, body2: Body): bool; + /** + * Separates the two objects on their y axis + * @param object1 The first GameObject to separate + * @param object2 The second GameObject to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. + */ + public separateBodyY(body1: Body, body2: Body): bool; + /** + * Checks for overlaps between two objects using the world QuadTree. Can be Sprite vs. Sprite, Sprite 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 Sprite or Group to check. If null the world.group is used. + * @param object2 The second Sprite or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + public overlap(object1?, object2?, notifyCallback?, processCallback?, context?): bool; + /** + * Collision resolution specifically for GameObjects vs. Tiles. + * @param object The GameObject to separate + * @param tile The Tile to separate + * @returns {boolean} Whether the objects in fact touched and were separated + */ + public separateTile(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool, separateX: bool, separateY: bool): bool; + } +} +/** * Phaser - World * * "This world is but a canvas to our imagination." - Henry David Thoreau @@ -4771,10 +6212,6 @@ module Phaser { */ public physics: Physics.PhysicsManager; /** - * @type {number} - */ - public worldDivisions: number; - /** * This is called automatically every frame, and is where main logic happens. */ public update(): void; @@ -4805,6 +6242,162 @@ module Phaser { } } /** +* Phaser - Motion +* +* The Motion class contains lots of useful functions for moving game objects around in world space. +*/ +module Phaser { + class Motion { + constructor(game: Game); + public game: Game; + /** + * Given the angle and speed calculate the velocity and return it as a Point + * + * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + public velocityFromAngle(angle: number, speed: number): Point; + /** + * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * If you need the object to accelerate, see accelerateTowardsObject() instead + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) + * + * @param {Sprite} source The Sprite on which the velocity will be set + * @param {Sprite} dest The Sprite where the source object will move to + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + public moveTowardsObject(source: Sprite, dest: Sprite, speed?: number, maxTime?: number): void; + /** + * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsObject() instead. + * + * @param {Sprite} source The Sprite on which the acceleration will be set + * @param {Sprite} dest The Sprite where the source object will move towards + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + public accelerateTowardsObject(source: Sprite, dest: Sprite, speed: number, xSpeedMax: number, ySpeedMax: number): void; + /** + * Move the given Sprite towards the mouse pointer coordinates at a steady velocity + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * + * @param {Sprite} source The Sprite to move + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + public moveTowardsMouse(source: Sprite, speed?: number, maxTime?: number): void; + /** + * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsMouse() instead. + * + * @param {Sprite} source The Sprite on which the acceleration will be set + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + public accelerateTowardsMouse(source: Sprite, speed: number, xSpeedMax: number, ySpeedMax: number): void; + /** + * Sets the x/y velocity on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * + * @param {Sprite} source The Sprite to move + * @param {Point} target The Point coordinates to move the source Sprite towards + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + public moveTowardsPoint(source: Sprite, target: Point, speed?: number, maxTime?: number): void; + /** + * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsPoint() instead. + * + * @param {Sprite} source The Sprite on which the acceleration will be set + * @param {Point} target The Point coordinates to move the source Sprite towards + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + public accelerateTowardsPoint(source: Sprite, target: Point, speed: number, xSpeedMax: number, ySpeedMax: number): void; + /** + * Find the distance between two Sprites, taking their origin into account + * + * @param {Sprite} a The first Sprite + * @param {Sprite} b The second Sprite + * @return {number} int Distance (in pixels) + */ + public distanceBetween(a: Sprite, b: Sprite): number; + /** + * Find the distance from an Sprite to the given Point, taking the source origin into account + * + * @param {Sprite} a The Sprite + * @param {Point} target The Point + * @return {number} Distance (in pixels) + */ + public distanceToPoint(a: Sprite, target: Point): number; + /** + * Find the distance (in pixels, rounded) from the object x/y and the mouse x/y + * + * @param {Sprite} a Sprite to test against + * @return {number} The distance between the given sprite and the mouse coordinates + */ + public distanceToMouse(a: Sprite): number; + /** + * Find the angle (in radians) between an Sprite and an Point. The source sprite takes its x/y and origin into account. + * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * + * @param {Sprite} a The Sprite to test from + * @param {Point} target The Point to angle the Sprite towards + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + public angleBetweenPoint(a: Sprite, target: Point, asDegrees?: bool): number; + /** + * Find the angle (in radians) between the two Sprite, taking their x/y and origin into account. + * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * + * @param {Sprite} a The Sprite to test from + * @param {Sprite} b The Sprite to test to + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + public angleBetween(a: Sprite, b: Sprite, asDegrees?: bool): number; + /** + * Given the Sprite and speed calculate the velocity and return it as an Point based on the direction the sprite is facing + * + * @param {Sprite} parent The Sprite to get the facing value from + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} An Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + public velocityFromFacing(parent: Sprite, speed: number): Point; + /** + * Find the angle (in radians) between an Sprite and the mouse, taking their x/y and origin into account. + * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * + * @param {Sprite} a The Object to test from + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + public angleBetweenMouse(a: Sprite, asDegrees?: bool): number; + } +} +/** * Phaser - Device * * Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr @@ -6143,139 +7736,6 @@ module Phaser { public renderScrollZone(camera: Camera, scrollZone: ScrollZone): bool; } } -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ -module Phaser { - class ScrollRegion { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. - * - * @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. - */ - 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; - /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - public visible: bool; - /** - * Region scrolling speed. - * @type {Vec2} - */ - public scrollSpeed: Vec2; - /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - public update(delta: number): void; - /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - public render(context: CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number): void; - /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY); - } -} -/** -* Phaser - ScrollZone -* -* Creates a scrolling region of the given width and height from an image in the cache. -* The ScrollZone can be positioned anywhere in-world like a normal game object, re-act to physics, collision, etc. -* The image within it is scrolled via ScrollRegions and their scrollSpeed.x/y properties. -* If you create a scroll zone larger than the given source image it will create a DynamicTexture and fill it with a pattern of the source image. -*/ -module Phaser { - class ScrollZone extends Sprite { - /** - * 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. - */ - constructor(game: Game, key: string, x?: number, y?: number, width?: number, height?: number); - /** - * Current region this zone is scrolling. - * @type {ScrollRegion} - */ - public currentRegion: ScrollRegion; - /** - * Array contains all added regions. - * @type {ScrollRegion[]} - */ - public regions: ScrollRegion[]; - /** - * Add a new region to this zone. - * @param x {number} X position of the new region. - * @param y {number} Y position of the new region. - * @param width {number} Width of the new region. - * @param height {number} Height of the new region. - * @param [speedX] {number} x-axis scrolling speed. - * @param [speedY] {number} y-axis scrolling speed. - * @return {ScrollRegion} The newly added region. - */ - public addRegion(x: number, y: number, width: number, height: number, speedX?: number, speedY?: number): ScrollRegion; - /** - * Set scrolling speed of current region. - * @param x {number} X speed of current region. - * @param y {number} Y speed of current region. - */ - public setSpeed(x: number, y: number): ScrollZone; - /** - * Update regions. - */ - public update(): void; - /** - * Create repeating texture with _texture, and store it into the _dynamicTexture. - * Used to create texture when texture image is small than size of the zone. - */ - private createRepeatingTexture(regionWidth, regionHeight); - } -} module Phaser { class CanvasRenderer implements IRenderer { constructor(game: Game); @@ -6435,6 +7895,11 @@ module Phaser { */ public math: GameMath; /** + * Reference to the motion helper. + * @type {Motion} + */ + public motion: Motion; + /** * Reference to the sound manager. * @type {SoundManager} */ @@ -6534,233 +7999,69 @@ module Phaser { public destroy(): void; public paused : bool; public framerate : number; + /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + public collide(objectOrGroup1?, objectOrGroup2?, notifyCallback?, context?): bool; public camera : Camera; } } /** -* Phaser - Vec2 +* Phaser - Components - Events +* * -* A Circle object is an area defined by its position, as indicated by its center point (x,y) and diameter. -*/ -module Phaser { - class Vec2 { - /** - * Creates a new Vec2 object. - * @class Vec2 - * @constructor - * @param {Number} x The x position of the vector - * @param {Number} y The y position of the vector - * @return {Vec2} This object - **/ - constructor(x?: number, y?: number); - /** - * The x coordinate of the vector - * @property x - * @type Number - **/ - public x: number; - /** - * The y coordinate of the vector - * @property y - * @type Number - **/ - public y: number; - /** - * Copies the x and y properties from any given object to this Vec2. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Vec2} This Vec2 object. - **/ - public copyFrom(source: any): Vec2; - /** - * Sets the x and y properties of the Vector. - * @param {Number} x The x position of the vector - * @param {Number} y The y position of the vector - * @return {Vec2} This object - **/ - public setTo(x: number, y: number): Vec2; - /** - * Add another vector to this one. - * - * @param {Vec2} other The other Vector. - * @return {Vec2} This for chaining. - */ - public add(a: Vec2): Vec2; - /** - * Subtract another vector from this one. - * - * @param {Vec2} other The other Vector. - * @return {Vec2} This for chaining. - */ - public subtract(v: Vec2): Vec2; - /** - * Multiply another vector with this one. - * - * @param {Vec2} other The other Vector. - * @return {Vec2} This for chaining. - */ - public multiply(v: Vec2): Vec2; - /** - * Divide this vector by another one. - * - * @param {Vec2} other The other Vector. - * @return {Vec2} This for chaining. - */ - public divide(v: Vec2): Vec2; - /** - * Get the length of this vector. - * - * @return {number} The length of this vector. - */ - public length(): number; - /** - * Get the length squared of this vector. - * - * @return {number} The length^2 of this vector. - */ - public lengthSq(): number; - /** - * The dot product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @return {Number} - */ - public dot(a: Vec2): number; - /** - * The cross product of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @return {Number} - */ - public cross(a: Vec2): number; - /** - * The projection magnitude of two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @return {Number} - */ - public projectionLength(a: Vec2): number; - /** - * The angle between two 2D vectors. - * - * @param {Vec2} a Reference to a source Vec2 object. - * @return {Number} - */ - public angle(a: Vec2): number; - /** - * Scale this vector. - * - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this is not specified, the x scaling factor will be used. - * @return {Vec2} This for chaining. - */ - public scale(x: number, y?: number): Vec2; - /** - * Multiply this vector by the given scalar. - * - * @param {number} scalar - * @return {Vec2} This for chaining. - */ - public multiplyByScalar(scalar: number): Vec2; - /** - * Divide this vector by the given scalar. - * - * @param {number} scalar - * @return {Vec2} This for chaining. - */ - public divideByScalar(scalar: number): Vec2; - /** - * Reverse this vector. - * - * @return {Vec2} This for chaining. - */ - public reverse(): Vec2; - /** - * Check if both the x and y of this vector equal the given value. - * - * @return {Boolean} - */ - public equals(value): bool; - /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the object. - **/ - public toString(): string; - } -} -/** -* Phaser - Physics - Circle -*/ -module Phaser.Physics { - class Circle implements IPhysicsShape { - constructor(game: Game, sprite: Sprite, x: number, y: number, diameter: number); - public game: Game; - public world: PhysicsManager; - public sprite: Sprite; - public physics: Components.Physics; - public position: Vec2; - public oldPosition: Vec2; - public offset: Vec2; - public scale: Vec2; - public bounds: Rectangle; - public radius: number; - public diameter: number; - public preUpdate(): void; - public update(): void; - public setSize(width: number, height: number): void; - public render(context: CanvasRenderingContext2D): void; - public hullWidth : number; - public hullHeight : number; - public hullX : number; - public hullY : number; - public deltaXAbs : number; - public deltaYAbs : number; - public deltaX : number; - public deltaY : number; - } -} -/** -* Phaser - Components - Physics */ module Phaser.Components { - class Physics { - constructor(parent: Sprite); + class Events { + constructor(parent: Sprite, key?: string); + /** + * + */ + private _game; + /** + * Reference to the Image stored in the Game.Cache that is used as the texture for the Sprite. + */ private _sprite; - public game: Game; - public shape: Physics.IPhysicsShape; + public onInputOver: Signal; + public onInputOut: Signal; + public onInputDown: Signal; + public onInputUp: Signal; + } +} +/** +* Phaser - Components - Debug +* +* +*/ +module Phaser.Components { + class Debug { /** - * Whether this object will be moved by impacts with other objects or not. + * Render bound of this sprite for debugging? (default to false) * @type {boolean} */ - public immovable: bool; + public renderDebug: bool; /** - * Set this to false if you want to skip the automatic movement stuff - * @type {boolean} + * Color of the Sprite when no image is present. Format is a css color string. + * @type {string} */ - public moves: bool; - public mass: number; - public gravity: Vec2; - public drag: Vec2; - public bounce: Vec2; - public friction: Vec2; - public velocity: Vec2; - public acceleration: Vec2; - public touching: number; - public allowCollisions: number; - public wasTouching: number; - public setCircle(diameter: number): void; + public fillColor: string; /** - * Internal function for updating the position and speed of this object. + * Color of bound when render debug. (see renderDebug) Format is a css color string. + * @type {string} */ - public update(): void; + public renderDebugColor: string; /** - * 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) + * Color of points when render debug. (see renderDebug) Format is a css color string. + * @type {string} */ - public renderDebugInfo(x: number, y: number, color?: string): void; + public renderDebugPointColor: string; } } /** @@ -6781,303 +8082,6 @@ module Phaser { } } /** -* Phaser - CircleUtils -* -* A collection of methods useful for manipulating and comparing Circle objects. -* -* TODO: -*/ -module Phaser { - class CircleUtils { - /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. - * @method clone - * @param {Circle} a - The Circle object. - * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} - **/ - static clone(a: Circle, out?: Circle): Circle; - /** - * Return true if the given x/y coordinates are within the Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method contains - * @param {Circle} a - The Circle object. - * @param {Number} The X value of the coordinate to test. - * @param {Number} The Y value of the coordinate to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - static contains(a: Circle, x: number, y: number): bool; - /** - * Return true if the coordinates of the given Point object are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method containsPoint - * @param {Circle} a - The Circle object. - * @param {Point} The Point object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - static containsPoint(a: Circle, point: Point): bool; - /** - * Return true if the given Circle is contained entirely within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. - * @method containsCircle - * @param {Circle} The Circle object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - static containsCircle(a: Circle, b: Circle): bool; - /** - * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) - * @method distanceBetween - * @param {Circle} a - The Circle object. - * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. - * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - static distanceBetween(a: Circle, target: any, round?: bool): number; - /** - * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. - * @method equals - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. - **/ - static equals(a: Circle, b: Circle): bool; - /** - * Determines whether the two Circle objects intersect. - * This method checks the radius distances between the two Circle objects to see if they intersect. - * @method intersects - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. - **/ - static intersects(a: Circle, b: Circle): bool; - /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method circumferencePoint - * @param {Circle} a - The first Circle object. - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - **/ - static circumferencePoint(a: Circle, angle: number, asDegrees?: bool, out?: Point): Point; - } -} -/** -* Phaser - LinkedList -* -* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! -*/ -module Phaser { - class LinkedList { - /** - * Creates a new link, and sets object and next to null. - */ - constructor(); - /** - * Stores a reference to an IGameObject. - */ - public object: IGameObject; - /** - * Stores a reference to the next link in the list. - */ - public next: LinkedList; - /** - * Clean up memory. - */ - public destroy(): void; - } -} -/** -* Phaser - QuadTree -* -* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. -* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, -* or the A list against the B list. Handy for different things! -*/ -module Phaser { - class QuadTree extends Rectangle { - /** - * Instantiate a new Quad Tree node. - * - * @param {Number} x The X-coordinate of the point in space. - * @param {Number} y The Y-coordinate of the point in space. - * @param {Number} width Desired width of this node. - * @param {Number} height Desired height of this node. - * @param {Number} parent The parent branch or node. Pass null to create a root. - */ - constructor(x: number, y: number, width: number, height: number, parent?: QuadTree); - private _iterator; - private _ot; - private _i; - private _basic; - private _members; - private _l; - private _overlapProcessed; - private _checkObject; - /** - * Flag for specifying that you want to add an object to the A list. - */ - static A_LIST: number; - /** - * Flag for specifying that you want to add an object to the B list. - */ - static B_LIST: number; - /** - * Controls the granularity of the quad tree. Default is 6 (decent performance on large and small worlds). - */ - static divisions: number; - /** - * Whether this branch of the tree can be subdivided or not. - */ - private _canSubdivide; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _headA; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _tailA; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _headB; - /** - * Refers to the internal A and B linked lists, - * which are used to store objects in the leaves. - */ - private _tailB; - /** - * Internal, governs and assists with the formation of the tree. - */ - private static _min; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _northWestTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _northEastTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _southEastTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _southWestTree; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _leftEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _rightEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _topEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _bottomEdge; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _halfWidth; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _halfHeight; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _midpointX; - /** - * Internal, governs and assists with the formation of the tree. - */ - private _midpointY; - /** - * Internal, used to reduce recursive method parameters during object placement and tree formation. - */ - private static _object; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _list; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _useBothLists; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _processingCallback; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _notifyCallback; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _callbackContext; - /** - * Internal, used during tree processing and overlap checks. - */ - private static _iterator; - /** - * Clean up memory. - */ - public destroy(): void; - /** - * Load objects and/or groups into the quad tree, and register notify and processing callbacks. - * - * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. - * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. - * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. - * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). - * @param context The context in which the callbacks will be called - */ - public load(objectOrGroup1, objectOrGroup2?, notifyCallback?, processCallback?, context?): void; - /** - * Call this function to add an object to the root of the tree. - * This function will recursively add all group members, but - * not the groups themselves. - * - * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. - * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. - */ - public add(objectOrGroup, list: number): void; - /** - * Internal function for recursively navigating and creating the tree - * while adding objects to the appropriate nodes. - */ - private addObject(); - /** - * Internal function for recursively adding objects to leaf lists. - */ - private addToList(); - /** - * QuadTree's other main function. Call this after adding objects - * using QuadTree.load() to compare the objects that you loaded. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - public execute(): bool; - /** - * A private for comparing an object against the contents of a node. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - private overlapNode(); - } -} -/** * Phaser - Line * * A Line object is an infinte line through space. The two sets of x/y coordinates define the Line Segment. diff --git a/build/phaser.js b/build/phaser.js index a3f9f003..c3baaccc 100644 --- a/build/phaser.js +++ b/build/phaser.js @@ -1,5 +1,2175 @@ /// /** +* 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.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 Math.round(this.width / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "halfHeight", { + get: /** + * Half of the height of the rectangle + * @property halfHeight + * @type Number + **/ + function () { + return Math.round(this.height / 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + get: /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @return {Number} + **/ + function () { + return this.y + this.height; + }, + set: /** + * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. + * @method bottom + * @param {Number} value + **/ + function (value) { + if(value <= this.y) { + this.height = 0; + } else { + this.height = (this.y - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottomRight", { + set: /** + * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. + * @method bottomRight + * @param {Point} value + **/ + function (value) { + this.right = value.x; + this.bottom = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "left", { + get: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. + * @method left + * @ return {number} + **/ + function () { + return this.x; + }, + set: /** + * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. + * However it does affect the width, whereas changing the x value does not affect the width property. + * @method left + * @param {Number} value + **/ + function (value) { + if(value >= this.right) { + this.width = 0; + } else { + this.width = this.right - value; + } + this.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + get: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @return {Number} + **/ + function () { + return this.x + this.width; + }, + set: /** + * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. + * However it does affect the width property. + * @method right + * @param {Number} value + **/ + function (value) { + if(value <= this.x) { + this.width = 0; + } else { + this.width = this.x + value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "volume", { + get: /** + * The volume of the Rectangle derived from width * height + * @method volume + * @return {Number} + **/ + function () { + return this.width * this.height; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "perimeter", { + get: /** + * The perimeter size of the Rectangle. This is the sum of all 4 sides. + * @method perimeter + * @return {Number} + **/ + function () { + return (this.width * 2) + (this.height * 2); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + get: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @return {Number} + **/ + function () { + return this.y; + }, + set: /** + * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. + * However it does affect the height property, whereas changing the y value does not affect the height property. + * @method top + * @param {Number} value + **/ + function (value) { + if(value >= this.bottom) { + this.height = 0; + this.y = value; + } else { + this.height = (this.bottom - value); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "topLeft", { + set: /** + * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. + * @method topLeft + * @param {Point} value + **/ + function (value) { + this.x = value.x; + this.y = value.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "empty", { + get: /** + * Determines whether or not this Rectangle object is empty. + * @method isEmpty + * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. + **/ + function () { + return (!this.width || !this.height); + }, + set: /** + * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. + * @method setEmpty + * @return {Rectangle} This rectangle object + **/ + function (value) { + return this.setTo(0, 0, 0, 0); + }, + enumerable: true, + configurable: true + }); + Rectangle.prototype.offset = /** + * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. + * @method offset + * @param {Number} dx Moves the x value of the Rectangle object by this amount. + * @param {Number} dy Moves the y value of the Rectangle object by this amount. + * @return {Rectangle} This Rectangle object. + **/ + function (dx, dy) { + this.x += dx; + this.y += dy; + return this; + }; + Rectangle.prototype.offsetPoint = /** + * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. + * @method offsetPoint + * @param {Point} point A Point object to use to offset this Rectangle object. + * @return {Rectangle} This Rectangle object. + **/ + function (point) { + return this.offset(point.x, point.y); + }; + Rectangle.prototype.setTo = /** + * Sets the members of Rectangle to the specified values. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the rectangle. + * @param {Number} y The y coordinate of the top-left corner of the rectangle. + * @param {Number} width The width of the rectangle in pixels. + * @param {Number} height The height of the rectangle in pixels. + * @return {Rectangle} This rectangle object + **/ + function (x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }; + Rectangle.prototype.copyFrom = /** + * Copies the x, y, width and height properties from any given object to this Rectangle. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {Rectangle} This Rectangle object. + **/ + function (source) { + return this.setTo(source.x, source.y, source.width, source.height); + }; + Rectangle.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; + }; + return Rectangle; + })(); + Phaser.Rectangle = Rectangle; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - LinkedList +* +* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! +*/ +var Phaser; +(function (Phaser) { + var LinkedList = (function () { + /** + * Creates a new link, and sets object and next to null. + */ + function LinkedList() { + this.object = null; + this.next = null; + } + LinkedList.prototype.destroy = /** + * Clean up memory. + */ + function () { + this.object = null; + if(this.next != null) { + this.next.destroy(); + } + this.next = null; + }; + return LinkedList; + })(); + Phaser.LinkedList = LinkedList; +})(Phaser || (Phaser = {})); +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/// +/** +* Phaser - QuadTree +* +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! +*/ +var Phaser; +(function (Phaser) { + var QuadTree = (function (_super) { + __extends(QuadTree, _super); + /** + * Instantiate a new Quad Tree node. + * + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. + */ + function QuadTree(x, y, width, height, parent) { + if (typeof parent === "undefined") { parent = null; } + _super.call(this, x, y, width, height); + this._headA = this._tailA = new Phaser.LinkedList(); + this._headB = this._tailB = new Phaser.LinkedList(); + //Copy the parent's children (if there are any) + if(parent != null) { + if(parent._headA.object != null) { + this._iterator = parent._headA; + while(this._iterator != null) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + if(parent._headB.object != null) { + this._iterator = parent._headB; + while(this._iterator != null) { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = this._iterator.object; + this._iterator = this._iterator.next; + } + } + } else { + QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); + } + this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); + //Set up comparison/sort helpers + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + this._leftEdge = this.x; + this._rightEdge = this.x + this.width; + this._halfWidth = this.width / 2; + this._midpointX = this._leftEdge + this._halfWidth; + this._topEdge = this.y; + this._bottomEdge = this.y + this.height; + this._halfHeight = this.height / 2; + this._midpointY = this._topEdge + this._halfHeight; + } + QuadTree.A_LIST = 0; + QuadTree.B_LIST = 1; + QuadTree.prototype.destroy = /** + * Clean up memory. + */ + function () { + this._tailA.destroy(); + this._tailB.destroy(); + this._headA.destroy(); + this._headB.destroy(); + this._tailA = null; + this._tailB = null; + this._headA = null; + this._headB = null; + if(this._northWestTree != null) { + this._northWestTree.destroy(); + } + if(this._northEastTree != null) { + this._northEastTree.destroy(); + } + if(this._southEastTree != null) { + this._southEastTree.destroy(); + } + if(this._southWestTree != null) { + this._southWestTree.destroy(); + } + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + QuadTree._object = null; + QuadTree._processingCallback = null; + QuadTree._notifyCallback = null; + }; + QuadTree.prototype.load = /** + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. + * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof processCallback === "undefined") { processCallback = null; } + if (typeof context === "undefined") { context = null; } + this.add(objectOrGroup1, QuadTree.A_LIST); + if(objectOrGroup2 != null) { + this.add(objectOrGroup2, QuadTree.B_LIST); + QuadTree._useBothLists = true; + } else { + QuadTree._useBothLists = false; + } + QuadTree._notifyCallback = notifyCallback; + QuadTree._processingCallback = processCallback; + QuadTree._callbackContext = context; + }; + QuadTree.prototype.add = /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + function (objectOrGroup, list) { + QuadTree._list = list; + if(objectOrGroup.type == Phaser.Types.GROUP) { + this._i = 0; + this._members = objectOrGroup['members']; + this._l = objectOrGroup['length']; + while(this._i < this._l) { + this._basic = this._members[this._i++]; + if(this._basic != null && this._basic.exists) { + if(this._basic.type == Phaser.Types.GROUP) { + this.add(this._basic, list); + } else { + QuadTree._object = this._basic; + if(QuadTree._object.exists && QuadTree._object.body.allowCollisions) { + this.addObject(); + } + } + } + } + } else { + QuadTree._object = objectOrGroup; + if(QuadTree._object.exists && QuadTree._object.body.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.body.bounds.x) && (this._rightEdge <= QuadTree._object.body.bounds.right) && (this._topEdge >= QuadTree._object.body.bounds.y) && (this._bottomEdge <= QuadTree._object.body.bounds.bottom))) { + this.addToList(); + return; + } + //See if the selected object fits completely inside any of the quadrants + if((QuadTree._object.body.bounds.x > this._leftEdge) && (QuadTree._object.body.bounds.right < this._midpointX)) { + if((QuadTree._object.body.bounds.y > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.y > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.x > this._midpointX) && (QuadTree._object.body.bounds.right < this._rightEdge)) { + if((QuadTree._object.body.bounds.y > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.y > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.right > this._leftEdge) && (QuadTree._object.body.bounds.x < this._midpointX) && (QuadTree._object.body.bounds.bottom > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.right > this._midpointX) && (QuadTree._object.body.bounds.x < this._rightEdge) && (QuadTree._object.body.bounds.bottom > this._topEdge) && (QuadTree._object.body.bounds.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.body.bounds.right > this._midpointX) && (QuadTree._object.body.bounds.x < this._rightEdge) && (QuadTree._object.body.bounds.bottom > this._midpointY) && (QuadTree._object.body.bounds.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.body.bounds.right > this._leftEdge) && (QuadTree._object.body.bounds.x < this._midpointX) && (QuadTree._object.body.bounds.bottom > this._midpointY) && (QuadTree._object.body.bounds.y < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + } + }; + QuadTree.prototype.addToList = /** + * Internal function for recursively adding objects to leaf lists. + */ + function () { + if(QuadTree._list == QuadTree.A_LIST) { + if(this._tailA.object != null) { + this._ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + this._ot.next = this._tailA; + } + this._tailA.object = QuadTree._object; + } else { + if(this._tailB.object != null) { + this._ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + this._ot.next = this._tailB; + } + this._tailB.object = QuadTree._object; + } + if(!this._canSubdivide) { + return; + } + if(this._northWestTree != null) { + this._northWestTree.addToList(); + } + if(this._northEastTree != null) { + this._northEastTree.addToList(); + } + if(this._southEastTree != null) { + this._southEastTree.addToList(); + } + if(this._southWestTree != null) { + this._southWestTree.addToList(); + } + }; + QuadTree.prototype.execute = /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + this._overlapProcessed = false; + if(this._headA.object != null) { + this._iterator = this._headA; + while(this._iterator != null) { + QuadTree._object = this._iterator.object; + if(QuadTree._useBothLists) { + QuadTree._iterator = this._headB; + } else { + QuadTree._iterator = this._iterator.next; + } + if(QuadTree._object.exists && (QuadTree._object.body.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { + this._overlapProcessed = true; + } + this._iterator = this._iterator.next; + } + } + //Advance through the tree by calling overlap on each child + if((this._northWestTree != null) && this._northWestTree.execute()) { + this._overlapProcessed = true; + } + if((this._northEastTree != null) && this._northEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southEastTree != null) && this._southEastTree.execute()) { + this._overlapProcessed = true; + } + if((this._southWestTree != null) && this._southWestTree.execute()) { + this._overlapProcessed = true; + } + return this._overlapProcessed; + }; + QuadTree.prototype.overlapNode = /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + //Walk the list and check for overlaps + this._overlapProcessed = false; + while(QuadTree._iterator != null) { + if(!QuadTree._object.exists || (QuadTree._object.body.allowCollisions <= 0)) { + break; + } + this._checkObject = QuadTree._iterator.object; + if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.body.allowCollisions <= 0)) { + QuadTree._iterator = QuadTree._iterator.next; + continue; + } + if(QuadTree._object.body.bounds.checkHullIntersection(this._checkObject.body.bounds)) { + //Execute callback functions if they exist + if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { + this._overlapProcessed = true; + } + if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { + if(QuadTree._callbackContext !== null) { + QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); + } else { + QuadTree._notifyCallback(QuadTree._object, this._checkObject); + } + } + } + QuadTree._iterator = QuadTree._iterator.next; + } + return this._overlapProcessed; + }; + return QuadTree; + })(Phaser.Rectangle); + Phaser.QuadTree = QuadTree; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - 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.multiplyByScalar = /** + * Multiply 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.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.equals = /** + * Check if both the x and y of this vector equal the given value. + * + * @return {Boolean} + */ + function (value) { + return (this.x == value && this.y == value); + }; + 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 - 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 * (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 = {})); +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; + Types.BODY_DISABLED = 0; + Types.BODY_DYNAMIC = 1; + Types.BODY_STATIC = 2; + Types.BODY_KINEMATIC = 3; + Types.LEFT = 0x0001; + Types.RIGHT = 0x0010; + Types.UP = 0x0100; + Types.DOWN = 0x1000; + Types.NONE = 0; + Types.CEILING = Types.UP; + Types.FLOOR = Types.DOWN; + Types.WALL = Types.LEFT | Types.RIGHT; + Types.ANY = Types.LEFT | Types.RIGHT | Types.UP | Types.DOWN; + return Types; + })(); + Phaser.Types = Types; +})(Phaser || (Phaser = {})); +/// +/// +/** +* Phaser - Group +* +* This class is used for organising, updating and sorting game objects. +*/ +var Phaser; +(function (Phaser) { + 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. + * If this value is set it will call a canvas context save and restore before and after the render pass. + * Set to null to disable. + */ + this.globalCompositeOperation = null; + /** + * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. + * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. + * Set to 0 to disable. + */ + this.alpha = 0; + this.game = game; + this.type = Phaser.Types.GROUP; + this.exists = true; + this.visible = true; + this.members = []; + this.length = 0; + this._maxSize = maxSize; + this._marker = 0; + this._sortIndex = null; + this.cameraBlacklist = []; + } + Group.ASCENDING = -1; + Group.DESCENDING = 1; + 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) { + 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; + } + this._sortIndex = null; + }; + Group.prototype.update = /** + * 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 () { + 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(); + this._member.postUpdate(); + } + } + }; + Group.prototype.render = /** + * 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 (renderer, camera) { + if(camera.isHidden(this) == true) { + return; + } + if(this.globalCompositeOperation) { + this.game.stage.context.save(); + this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation; + } + if(this.alpha > 0) { + this._prevAlpha = this.game.stage.context.globalAlpha; + this.game.stage.context.globalAlpha = this.alpha; + } + 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.call(renderer, camera, this._member); + } + } + if(this.alpha > 0) { + this.game.stage.context.globalAlpha = this._prevAlpha; + } + if(this.globalCompositeOperation) { + this.game.stage.context.restore(); + } + }; + Object.defineProperty(Group.prototype, "maxSize", { + get: /** + * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. + */ + function () { + return this._maxSize; + }, + set: /** + * @private + */ + function (Size) { + this._maxSize = Size; + if(this._marker >= this._maxSize) { + this._marker = 0; + } + 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 + 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; + }, + enumerable: true, + configurable: true + }); + Group.prototype.add = /** + * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. + * Group will try to replace a null member of the array first. + * Failing that, Group will add it to the end of the member array, + * assuming there is room for it, and doubling the size of the array if necessary. + * + *

WARNING: If the group has a maxSize that has already been met, + * the object will NOT be added to the group!

+ * + * @param {Basic} Object The object you want to add to the group. + * @return {Basic} The same Basic object that was passed in. + */ + function (object) { + //Don't bother adding an object twice. + if(this.members.indexOf(Object) >= 0) { + return object; + } + //First, look for a null entry where we can add the object. + 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; + } + 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; + } else if(this.members.length * 2 <= this._maxSize) { + this.members.length *= 2; + } else { + this.members.length = this._maxSize; + } + } else { + this.members.length *= 2; + } + //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[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. + * + *

If you specified a maximum size for this group (like in Emitter), + * then recycle will employ what we're calling "rotating" recycling. + * Recycle() will first check to see if the group is at capacity yet. + * If group is not yet at capacity, recycle() returns a new object. + * If the group IS at capacity, then recycle() just returns the next object in line.

+ * + *

If you did NOT specify a maximum size for this group, + * then recycle() will employ what we're calling "grow-style" recycling. + * Recycle() will return either the first object with exists == false, + * or, finding none, add a new object to the array, + * doubling the size of the array if necessary.

+ * + *

WARNING: If this function needs to create a new object, + * and no object class was provided, it will return null + * instead of a valid object!

+ * + * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! + * + * @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; } + if(this._maxSize > 0) { + if(this.length < this._maxSize) { + if(objectClass == null) { + return null; + } + return this.add(new objectClass(this.game)); + } else { + this._member = this.members[this._marker++]; + if(this._marker >= this._maxSize) { + this._marker = 0; + } + return this._member; + } + } else { + this._member = this.getFirstAvailable(objectClass); + if(this._member != null) { + return this._member; + } + if(objectClass == null) { + return null; + } + return this.add(new objectClass(this.game)); + } + }; + Group.prototype.remove = /** + * Removes an object from the group. + * + * @param {Basic} object The Basic you want to remove. + * @param {boolean} splice Whether the object should be cut from the array entirely or not. + * + * @return {Basic} The removed object. + */ + function (object, splice) { + if (typeof splice === "undefined") { splice = false; } + this._i = this.members.indexOf(object); + if(this._i < 0 || (this._i >= this.members.length)) { + return null; + } + if(splice) { + this.members.splice(this._i, 1); + this.length--; + } else { + this.members[this._i] = null; + } + return object; + }; + Group.prototype.replace = /** + * Replaces an existing Basic with a new one. + * + * @param {Basic} oldObject The object you want to replace. + * @param {Basic} newObject The new object you want to use instead. + * + * @return {Basic} The new object. + */ + function (oldObject, newObject) { + this._i = this.members.indexOf(oldObject); + if(this._i < 0 || (this._i >= this.members.length)) { + return null; + } + this.members[this._i] = newObject; + return newObject; + }; + Group.prototype.sort = /** + * Call this function to sort the group according to a particular value and order. + * For example, to sort game objects for Zelda-style overlaps you might call + * myGroup.sort("y",Group.ASCENDING) at the bottom of your + * State.update() override. To sort all existing objects after + * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). + * + * @param {string} index The string name of the member variable you want to sort on. Default value is "y". + * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. + */ + function (index, order) { + if (typeof index === "undefined") { index = "y"; } + if (typeof order === "undefined") { order = Group.ASCENDING; } + this._sortIndex = index; + this._sortOrder = order; + this.members.sort(this.sortHandler); + }; + Group.prototype.setAll = /** + * Go through and set the specified variable to the specified value on all members of the group. + * + * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". + * @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; } + 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 { + this._member[variableName] = value; + } + } + } + }; + Group.prototype.callAll = /** + * Go through and call the specified function on all members of the group. + * Currently only works on functions that have no required parameters. + * + * @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; } + 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 { + this._member[functionName](); + } + } + } + }; + Group.prototype.forEach = /** + * @param {function} callback + * @param {boolean} recursive + */ + function (callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + 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, this._member); + } + } + } + }; + Group.prototype.forEachAlive = /** + * @param {any} context + * @param {function} callback + * @param {boolean} recursive + */ + function (context, callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + 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, this._member); + } + } + } + }; + Group.prototype.getFirstAvailable = /** + * Call this function to retrieve the first object with exists == false in the group. + * This is handy for recycling in general, e.g. respawning enemies. + * + * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. + * + * @return {any} A Basic currently flagged as not existing. + */ + 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; + }; + Group.prototype.getFirstNull = /** + * Call this function to retrieve the first index set to 'null'. + * Returns -1 if no index stores a null object. + * + * @return {number} An int indicating the first null slot in the group. + */ + function () { + this._i = 0; + while(this._i < this.length) { + if(this.members[this._i] == null) { + return this._i; + } else { + this._i++; + } + } + return -1; + }; + Group.prototype.getFirstExtant = /** + * Call this function to retrieve the first object with exists == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as existing. + */ + function () { + 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; + }; + Group.prototype.getFirstAlive = /** + * Call this function to retrieve the first object with dead == false in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as not dead. + */ + function () { + 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; + }; + Group.prototype.getFirstDead = /** + * Call this function to retrieve the first object with dead == true in the group. + * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. + * + * @return {Basic} A Basic currently flagged as dead. + */ + function () { + 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; + }; + Group.prototype.countLiving = /** + * Call this function to find out how many members of the group are not dead. + * + * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. + */ + function () { + 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(this._member.exists && this._member.alive) { + this._count++; + } + } + } + return this._count; + }; + Group.prototype.countDead = /** + * Call this function to find out how many members of the group are dead. + * + * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. + */ + function () { + 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(!this._member.alive) { + this._count++; + } + } + } + return this._count; + }; + Group.prototype.getRandom = /** + * Returns a member at random from the group. + * + * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param {number} Length Optional restriction on the number of values you want to randomly select from. + * + * @return {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; + } + return this.game.math.getRandom(this.members, startIndex, length); + }; + Group.prototype.clear = /** + * Remove all instances of Basic subclass (Basic, Block, etc) from the list. + * WARNING: does not destroy() or kill() any of these objects! + */ + function () { + this.length = this.members.length = 0; + }; + Group.prototype.kill = /** + * Calls kill on the group's members and then on the group itself. + */ + function () { + this._i = 0; + while(this._i < this.length) { + this._member = this.members[this._i++]; + if((this._member != null) && this._member.exists) { + this._member.kill(); + } + } + }; + Group.prototype.sortHandler = /** + * Helper function for the sort process. + * + * @param {Basic} Obj1 The first object being sorted. + * @param {Basic} Obj2 The second object being sorted. + * + * @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]) { + return this._sortOrder; + } else if(obj1[this._sortIndex] > obj2[this._sortIndex]) { + return -this._sortOrder; + } + return 0; + }; + return Group; + })(); + Phaser.Group = Group; +})(Phaser || (Phaser = {})); +/// +/** +* Phaser - SignalBinding +* +* An object that represents a binding between a Signal and a listener function. +* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. +* Released under the MIT license +* http://millermedeiros.github.com/js-signals/ +*/ +var Phaser; +(function (Phaser) { + var SignalBinding = (function () { + /** + * Object that represents a binding between a Signal and a listener function. + *
- This is an internal constructor and shouldn't be called by regular users. + *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. + * @author Miller Medeiros + * @constructor + * @internal + * @name SignalBinding + * @param {Signal} signal Reference to Signal object that listener is currently bound to. + * @param {Function} listener Handler function bound to the signal. + * @param {boolean} isOnce If binding should be executed just once. + * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). + * @param {Number} [priority] The priority level of the event listener. (default = 0). + */ + function SignalBinding(signal, listener, isOnce, listenerContext, priority) { + if (typeof priority === "undefined") { priority = 0; } + /** + * If binding is active and should be executed. + * @type boolean + */ + this.active = true; + /** + * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) + * @type Array|null + */ + this.params = null; + this._listener = listener; + this._isOnce = isOnce; + this.context = listenerContext; + this._signal = signal; + this.priority = priority || 0; + } + SignalBinding.prototype.execute = /** + * Call listener passing arbitrary parameters. + *

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

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

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

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

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

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

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

+ */ + function () { + this.removeAll(); + delete this._bindings; + delete this._prevParams; + }; + Signal.prototype.toString = /** + * @return {string} String representation of the object. + */ + function () { + return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; + }; + return Signal; + })(); + Phaser.Signal = Signal; +})(Phaser || (Phaser = {})); +/// +/** * Phaser - Loader * * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. @@ -678,7 +2848,7 @@ var Phaser; * The global random number generator seed (for deterministic behavior in recordings and saves). */ this.globalSeed = Math.random(); - this._game = game; + this.game = game; } GameMath.PI = 3.141592653589793; GameMath.PI_2 = 1.5707963267948965; @@ -1296,7 +3466,7 @@ var Phaser; * @method linear * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var m = v.length - 1; @@ -1314,7 +3484,7 @@ var Phaser; * @method Bezier * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var b = 0; @@ -1328,7 +3498,7 @@ var Phaser; * @method CatmullRom * @param {Any} v * @param {Any} k - * @static + * @public */ function (v, k) { var m = v.length - 1; @@ -1354,7 +3524,7 @@ var Phaser; * @param {Any} p0 * @param {Any} p1 * @param {Any} t - * @static + * @public */ function (p0, p1, t) { return (p1 - p0) * t + p0; @@ -1363,7 +3533,7 @@ var Phaser; * @method Bernstein * @param {Any} n * @param {Any} i - * @static + * @public */ function (n, i) { return this.factorial(n) / this.factorial(i) / this.factorial(n - i); @@ -1375,7 +3545,7 @@ var Phaser; * @param {Any} p2 * @param {Any} p3 * @param {Any} t - * @static + * @public */ function (p0, p1, p2, p3, t) { var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; @@ -1504,30 +3674,6 @@ var Phaser; return s; } }; - GameMath.prototype.vectorLength = /** - * Finds the length of the given vector - * - * @param dx - * @param dy - * - * @return - */ - function (dx, dy) { - return Math.sqrt(dx * dx + dy * dy); - }; - GameMath.prototype.dotProduct = /** - * Finds the dot product value of two vectors - * - * @param ax Vector X - * @param ay Vector Y - * @param bx Vector X - * @param by Vector Y - * - * @return Dot product - */ - function (ax, ay, bx, by) { - return ax * bx + ay * by; - }; GameMath.prototype.shuffleArray = /** * Shuffles the data in the given array into a new order * @param array The array to shuffle @@ -1542,18 +3688,29 @@ var Phaser; } return array; }; - GameMath.distanceBetween = /** + GameMath.prototype.distanceBetween = /** * Returns the distance from this Point object to the given Point object. * @method distanceFrom * @param {Point} target - The destination Point object. * @param {Boolean} round - Round the distance to the nearest integer (default false) * @return {Number} The distance between this Point object and the destination Point object. **/ - function distanceBetween(x1, y1, x2, y2) { + function (x1, y1, x2, y2) { var dx = x1 - x2; var dy = y1 - y2; return Math.sqrt(dx * dx + dy * dy); }; + GameMath.prototype.vectorLength = /** + * Finds the length of the given vector + * + * @param dx + * @param dy + * + * @return + */ + function (dx, 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 * @param point {Object} Any object with exposed x and y properties @@ -1811,356 +3968,6 @@ var Phaser; })(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.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 Math.round(this.width / 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "halfHeight", { - get: /** - * Half of the height of the rectangle - * @property halfHeight - * @type Number - **/ - function () { - return Math.round(this.height / 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottom", { - get: /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @return {Number} - **/ - function () { - return this.y + this.height; - }, - set: /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @param {Number} value - **/ - function (value) { - if(value <= this.y) { - this.height = 0; - } else { - this.height = (this.y - value); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottomRight", { - set: /** - * Sets the bottom-right corner of the Rectangle, determined by the values of the given Point object. - * @method bottomRight - * @param {Point} value - **/ - function (value) { - this.right = value.x; - this.bottom = value.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "left", { - get: /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. - * @method left - * @ return {number} - **/ - function () { - return this.x; - }, - set: /** - * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. - * However it does affect the width, whereas changing the x value does not affect the width property. - * @method left - * @param {Number} value - **/ - function (value) { - if(value >= this.right) { - this.width = 0; - } else { - this.width = this.right - value; - } - this.x = value; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "right", { - get: /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {Number} - **/ - function () { - return this.x + this.width; - }, - set: /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {Number} value - **/ - function (value) { - if(value <= this.x) { - this.width = 0; - } else { - this.width = this.x + value; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "volume", { - get: /** - * The volume of the Rectangle derived from width * height - * @method volume - * @return {Number} - **/ - function () { - return this.width * this.height; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "perimeter", { - get: /** - * The perimeter size of the Rectangle. This is the sum of all 4 sides. - * @method perimeter - * @return {Number} - **/ - function () { - return (this.width * 2) + (this.height * 2); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "top", { - get: /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @return {Number} - **/ - function () { - return this.y; - }, - set: /** - * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. - * However it does affect the height property, whereas changing the y value does not affect the height property. - * @method top - * @param {Number} value - **/ - function (value) { - if(value >= this.bottom) { - this.height = 0; - this.y = value; - } else { - this.height = (this.bottom - value); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "topLeft", { - set: /** - * The location of the Rectangles top-left corner, determined by the x and y coordinates of the Point. - * @method topLeft - * @param {Point} value - **/ - function (value) { - this.x = value.x; - this.y = value.y; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "empty", { - get: /** - * Determines whether or not this Rectangle object is empty. - * @method isEmpty - * @return {Boolean} A value of true if the Rectangle object's width or height is less than or equal to 0; otherwise false. - **/ - function () { - return (!this.width || !this.height); - }, - set: /** - * Sets all of the Rectangle object's properties to 0. A Rectangle object is empty if its width or height is less than or equal to 0. - * @method setEmpty - * @return {Rectangle} This rectangle object - **/ - function (value) { - return this.setTo(0, 0, 0, 0); - }, - enumerable: true, - configurable: true - }); - Rectangle.prototype.offset = /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method offset - * @param {Number} dx Moves the x value of the Rectangle object by this amount. - * @param {Number} dy Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - function (dx, dy) { - this.x += dx; - this.y += dy; - return this; - }; - Rectangle.prototype.offsetPoint = /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method offsetPoint - * @param {Point} point A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - function (point) { - return this.offset(point.x, point.y); - }; - Rectangle.prototype.setTo = /** - * Sets the members of Rectangle to the specified values. - * @method setTo - * @param {Number} x The x coordinate of the top-left corner of the rectangle. - * @param {Number} y The y coordinate of the top-left corner of the rectangle. - * @param {Number} width The width of the rectangle in pixels. - * @param {Number} height The height of the rectangle in pixels. - * @return {Rectangle} This rectangle object - **/ - function (x, y, width, height) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - return this; - }; - Rectangle.prototype.copyFrom = /** - * Copies the x, y, width and height properties from any given object to this Rectangle. - * @method copyFrom - * @param {any} source - The object to copy from. - * @return {Rectangle} This Rectangle object. - **/ - function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }; - Rectangle.prototype.toString = /** - * Returns a string representation of this object. - * @method toString - * @return {string} a string representation of the instance. - **/ - function () { - return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; - }; - return Rectangle; - })(); - Phaser.Rectangle = Rectangle; -})(Phaser || (Phaser = {})); -/// -/** * Phaser - AnimationLoader * * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. @@ -3232,291 +5039,6 @@ var Phaser; 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; - /** - * 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 = {})); -/// /// /// /// @@ -3525,22 +5047,11 @@ var 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.getAsPoints = function getAsPoints(sprite) { var out = []; // top left @@ -3553,7 +5064,7 @@ var Phaser; out.push(new Phaser.Point(sprite.x, sprite.y + sprite.height)); return out; }; - SpriteUtils.setBounds = /** + SpriteUtils.onScreen = /** * 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! @@ -3698,51 +5209,38 @@ var Phaser; * * @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); - - } - */ - /** + function onScreen(sprite, camera) { + if (typeof camera === "undefined") { camera = null; } + if(camera == null) { + camera = sprite.game.camera; + } + SpriteUtils.getScreenXY(sprite, SpriteUtils._tempPoint, camera); + return (SpriteUtils._tempPoint.x + sprite.width > 0) && (SpriteUtils._tempPoint.x < camera.width) && (SpriteUtils._tempPoint.y + sprite.height > 0) && (SpriteUtils._tempPoint.y < camera.height); + }; + SpriteUtils.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. + * @return {Point} The Point 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; - - } - */ - /** + function getScreenXY(sprite, point, camera) { + if (typeof point === "undefined") { point = null; } + if (typeof camera === "undefined") { camera = null; } + if(point == null) { + point = new Phaser.Point(); + } + if(camera == null) { + camera = this._game.camera; + } + point.x = sprite.x - camera.scroll.x * sprite.scrollFactor.x; + point.y = sprite.y - camera.scroll.y * sprite.scrollFactor.y; + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + return point; + }; + SpriteUtils.inCamera = /** * 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 @@ -3760,47 +5258,34 @@ var 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. */ - /* - 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); - - } - */ - /** + function inCamera(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); + }; + SpriteUtils.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. */ - /* - 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; - - } - */ - /** + function reset(sprite, x, y) { + sprite.revive(); + sprite.body.touching = Phaser.Types.NONE; + sprite.body.wasTouching = Phaser.Types.NONE; + sprite.x = x; + sprite.y = y; + sprite.body.velocity.x = 0; + sprite.body.velocity.y = 0; + }; + SpriteUtils.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. @@ -4281,1100 +5766,11 @@ var Phaser; } */ })(Phaser || (Phaser = {})); -/// -/// -/// -/// -/** -* Phaser - CircleUtils -* -* A collection of methods useful for manipulating and comparing Circle objects. -* -* TODO: -*/ -var Phaser; -(function (Phaser) { - var CircleUtils = (function () { - function CircleUtils() { } - CircleUtils.clone = /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. - * @method clone - * @param {Circle} a - The Circle object. - * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} - **/ - function clone(a, out) { - if (typeof out === "undefined") { out = new Phaser.Circle(); } - return out.setTo(a.x, a.y, a.diameter); - }; - CircleUtils.contains = /** - * Return true if the given x/y coordinates are within the Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method contains - * @param {Circle} a - The Circle object. - * @param {Number} The X value of the coordinate to test. - * @param {Number} The Y value of the coordinate to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function contains(a, x, y) { - //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); - return true; - }; - CircleUtils.containsPoint = /** - * Return true if the coordinates of the given Point object are within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. - * @method containsPoint - * @param {Circle} a - The Circle object. - * @param {Point} The Point object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function containsPoint(a, point) { - return CircleUtils.contains(a, point.x, point.y); - }; - CircleUtils.containsCircle = /** - * Return true if the given Circle is contained entirely within this Circle object. - * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. - * @method containsCircle - * @param {Circle} The Circle object to test. - * @return {Boolean} True if the coordinates are within this circle, otherwise false. - **/ - function containsCircle(a, b) { - //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); - return true; - }; - CircleUtils.distanceBetween = /** - * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) - * @method distanceBetween - * @param {Circle} a - The Circle object. - * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. - * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between this Point object and the destination Point object. - **/ - function distanceBetween(a, target, round) { - if (typeof round === "undefined") { round = false; } - var dx = a.x - target.x; - var dy = a.y - target.y; - if(round === true) { - return Math.round(Math.sqrt(dx * dx + dy * dy)); - } else { - return Math.sqrt(dx * dx + dy * dy); - } - }; - CircleUtils.equals = /** - * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. - * @method equals - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. - **/ - function equals(a, b) { - return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); - }; - CircleUtils.intersects = /** - * Determines whether the two Circle objects intersect. - * This method checks the radius distances between the two Circle objects to see if they intersect. - * @method intersects - * @param {Circle} a - The first Circle object. - * @param {Circle} b - The second Circle object. - * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. - **/ - function intersects(a, b) { - return (CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); - }; - CircleUtils.circumferencePoint = /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method circumferencePoint - * @param {Circle} a - The first Circle object. - * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. - * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - **/ - function circumferencePoint(a, angle, asDegrees, out) { - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof out === "undefined") { out = new Phaser.Point(); } - if(asDegrees === true) { - angle = angle * Phaser.GameMath.DEG_TO_RAD; - } - return out.setTo(a.x + a.radius * Math.cos(angle), a.y + a.radius * Math.sin(angle)); - }; - CircleUtils.intersectsRectangle = /* - public static boolean intersect(Rectangle r, Circle c) - { - float cx = Math.abs(c.x - r.x - r.halfWidth); - float xDist = r.halfWidth + c.radius; - if (cx > xDist) - return false; - float cy = Math.abs(c.y - r.y - r.halfHeight); - float yDist = r.halfHeight + c.radius; - if (cy > yDist) - return false; - if (cx <= r.halfWidth || cy <= r.halfHeight) - return true; - float xCornerDist = cx - r.halfWidth; - float yCornerDist = cy - r.halfHeight; - float xCornerDistSq = xCornerDist * xCornerDist; - float yCornerDistSq = yCornerDist * yCornerDist; - float maxCornerDistSq = c.radius * c.radius; - return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; - } - */ - function intersectsRectangle(c, r) { - var cx = Math.abs(c.x - r.x - r.halfWidth); - var xDist = r.halfWidth + c.radius; - if(cx > xDist) { - return false; - } - var cy = Math.abs(c.y - r.y - r.halfHeight); - var yDist = r.halfHeight + c.radius; - if(cy > yDist) { - return false; - } - if(cx <= r.halfWidth || cy <= r.halfHeight) { - return true; - } - var xCornerDist = cx - r.halfWidth; - var yCornerDist = cy - r.halfHeight; - var xCornerDistSq = xCornerDist * xCornerDist; - var yCornerDistSq = yCornerDist * yCornerDist; - var maxCornerDistSq = c.radius * c.radius; - return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; - }; - return CircleUtils; - })(); - Phaser.CircleUtils = CircleUtils; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /** - * Phaser - PhysicsManager - * - * Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding - * all of the physics objects in the world. - */ - (function (Physics) { - var PhysicsManager = (function () { - function PhysicsManager(game, width, height) { - this._length = 0; - this.game = game; - this.gravity = new Phaser.Vec2(); - this.drag = new Phaser.Vec2(); - this.bounce = new Phaser.Vec2(); - this.angularDrag = 0; - this.bounds = new Phaser.Rectangle(0, 0, width, height); - this._distance = new Phaser.Vec2(); - this._tangent = new Phaser.Vec2(); - this._objects = []; - } - PhysicsManager.OVERLAP_BIAS = 4; - PhysicsManager.prototype.updateMotion = // Add some sanity checks here + remove method, etc - /* - public add(shape: IPhysicsShape): IPhysicsShape { - - this._objects.push(shape); - return shape; - - } - - public remove(shape: IPhysicsShape) { - - this._length = this._objects.length; - - for (var i = 0; i < this._length; i++) - { - if (this._objects[i] === shape) - { - this._objects[i] = null; - } - } - - } - - public update() { - - this._length = this._objects.length; - - for (var i = 0; i < this._length; i++) - { - if (this._objects[i]) - { - this._objects[i].preUpdate(); - this.updateMotion(this._objects[i]); - this.collideWorld(this._objects[i]); - - for (var x = 0; x < this._length; x++) - { - if (this._objects[x] && this._objects[x] !== this._objects[i]) - { - //this.collideShapes(this._objects[i], this._objects[x]); - var r = this.NEWseparate(this._objects[i], this._objects[x]); - //console.log('sep', r); - } - } - - } - } - - } - - public render() { - - // iterate through the objects here, updating and colliding - for (var i = 0; i < this._length; i++) - { - if (this._objects[i]) - { - this._objects[i].render(this.game.stage.context); - } - } - - } - */ - function (body) { - if(body.type == Phaser.Types.BODY_DISABLED) { - return; - } - this._velocityDelta = (this.computeVelocity(body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity) / 2; - body.angularVelocity += this._velocityDelta; - body.angle += body.angularVelocity * this.game.time.elapsed; - body.angularVelocity += this._velocityDelta; - this._velocityDelta = (this.computeVelocity(body.velocity.x, body.gravity.x, body.acceleration.x, body.drag.x) - body.velocity.x) / 2; - body.velocity.x += this._velocityDelta; - this._delta = body.velocity.x * this.game.time.elapsed; - body.velocity.x += this._velocityDelta; - body.position.x += this._delta; - this._velocityDelta = (this.computeVelocity(body.velocity.y, body.gravity.y, body.acceleration.y, body.drag.y) - body.velocity.y) / 2; - body.velocity.y += this._velocityDelta; - this._delta = body.velocity.y * this.game.time.elapsed; - body.velocity.y += this._velocityDelta; - body.position.y += this._delta; - }; - PhysicsManager.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. - */ - function (velocity, gravity, acceleration, drag, max) { - if (typeof gravity === "undefined") { gravity = 0; } - if (typeof acceleration === "undefined") { acceleration = 0; } - if (typeof drag === "undefined") { drag = 0; } - if (typeof max === "undefined") { max = 10000; } - if(acceleration !== 0) { - velocity += (acceleration + gravity) * this.game.time.elapsed; - } else if(drag !== 0) { - this._drag = drag * this.game.time.elapsed; - if(velocity - this._drag > 0) { - velocity = velocity - this._drag; - } else if(velocity + this._drag < 0) { - velocity += this._drag; - } else { - velocity = 0; - } - velocity += gravity; - } - if((velocity != 0) && (max != 10000)) { - if(velocity > max) { - velocity = max; - } else if(velocity < -max) { - velocity = -max; - } - } - return velocity; - }; - PhysicsManager.prototype.collideShapes = function (shapeA, shapeB) { - if(shapeA.physics.immovable && shapeB.physics.immovable) { - return; - } - this._distance.setTo(0, 0); - this._tangent.setTo(0, 0); - // Simple bounds check first - if(Phaser.RectangleUtils.intersects(shapeA.bounds, shapeB.bounds)) { - // Collide on the x-axis - if(shapeA.physics.velocity.x > 0 && shapeA.bounds.right > shapeB.bounds.x && shapeA.bounds.right <= shapeB.bounds.right) { - // The right side of ShapeA hit the left side of ShapeB - this._distance.x = shapeB.bounds.x - shapeA.bounds.right; - if(this._distance.x != 0) { - this._tangent.x = -1; - } - } else if(shapeA.physics.velocity.x < 0 && shapeA.bounds.x < shapeB.bounds.right && shapeA.bounds.x >= shapeB.bounds.x) { - // The left side of ShapeA hit the right side of ShapeB - this._distance.x = shapeB.bounds.right - shapeA.bounds.x; - if(this._distance.x != 0) { - this._tangent.x = 1; - } - } - // Collide on the y-axis - if(shapeA.physics.velocity.y < 0 && shapeA.bounds.y < shapeB.bounds.bottom && shapeA.bounds.y > shapeB.bounds.y) { - console.log('top A -> bot B'); - // The top of ShapeA hit the bottom of ShapeB - this._distance.y = shapeB.bounds.bottom - shapeA.bounds.y; - console.log(shapeA.bounds, shapeB.bounds, this._distance.y); - if(this._distance.y != 0) { - this._tangent.y = 1; - } - } else if(shapeA.physics.velocity.y > 0 && shapeA.bounds.bottom > shapeB.bounds.y && shapeA.bounds.bottom < shapeB.bounds.bottom) { - // The bottom of ShapeA hit the top of ShapeB - this._distance.y = shapeB.bounds.y - shapeA.bounds.bottom; - if(this._distance.y != 0) { - this._tangent.y = -1; - } - } - // Separate - if(this._distance.equals(0) == false) { - //this.separate(shapeA, shapeB, this._distance, this._tangent); - } - } - }; - PhysicsManager.prototype.separate = /** - * The core Collision separation method. - * @param body1 The first Physics.Body to separate - * @param body2 The second Physics.Body to separate - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - function (body1, body2) { - this._separatedX = this.separateBodyX(body1, body2); - this._separatedY = this.separateBodyY(body1, body2); - return this._separatedX || this._separatedY; - }; - PhysicsManager.prototype.checkHullIntersection = function (shape1, shape2) { - //if ((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.bounds.width) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) - // maybe not bounds.width? - if((shape1.hullX + shape1.hullWidth > shape2.hullX) && (shape1.hullX < shape2.hullX + shape2.hullWidth) && (shape1.hullY + shape1.hullHeight > shape2.hullY) && (shape1.hullY < shape2.hullY + shape2.hullHeight)) { - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.separateBodyX = /** - * 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 (body1, body2) { - // Can't separate two disabled or static objects - if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { - return false; - } - // First, get the two object deltas - this._overlap = 0; - if(body1.deltaX != body2.deltaX) { - if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { - this._maxOverlap = body1.deltaXAbs + body2.deltaXAbs + PhysicsManager.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(body1.deltaX > body2.deltaX) { - this._overlap = body1.bounds.right - body2.bounds.x; - if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.RIGHT) || !(body2.allowCollisions & Phaser.Types.LEFT)) { - this._overlap = 0; - } else { - body1.touching |= Phaser.Types.RIGHT; - body2.touching |= Phaser.Types.LEFT; - } - } else if(body1.deltaX < body2.deltaX) { - this._overlap = body1.bounds.x - body2.bounds.width - body2.bounds.x; - if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.LEFT) || !(body2.allowCollisions & Phaser.Types.RIGHT)) { - this._overlap = 0; - } else { - body1.touching |= Phaser.Types.LEFT; - body2.touching |= Phaser.Types.RIGHT; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(this._overlap != 0) { - this._obj1Velocity = body1.velocity.x; - this._obj2Velocity = body2.velocity.x; - /** - * Dynamic = gives and receives impacts - * Static = gives but doesn't receive impacts, cannot be moved by physics - * Kinematic = gives impacts, but never receives, can be moved by physics - */ - // 2 dynamic bodies will exchange velocities - if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { - this._overlap *= 0.5; - body1.position.x = body1.position.x - this._overlap; - body2.position.x += this._overlap; - this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); - this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); - this._average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; - this._obj1NewVelocity -= this._average; - this._obj2NewVelocity -= this._average; - body1.velocity.x = this._average + this._obj1NewVelocity * body1.bounce.x; - body2.velocity.x = this._average + this._obj2NewVelocity * body2.bounce.x; - } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { - // Body 2 is Static or Kinematic - this._overlap *= 2; - body1.position.x -= this._overlap; - body1.velocity.x = this._obj2Velocity - this._obj1Velocity * body1.bounce.x; - } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { - // Body 1 is Static or Kinematic - this._overlap *= 2; - body2.position.x += this._overlap; - body2.velocity.x = this._obj1Velocity - this._obj2Velocity * body2.bounce.x; - } - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.separateBodyY = /** - * 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 (body1, body2) { - // Can't separate two immovable objects - if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { - return false; - } - // First, get the two object deltas - this._overlap = 0; - if(body1.deltaY != body2.deltaY) { - if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { - // This is the only place to use the DeltaAbs values - this._maxOverlap = body1.deltaYAbs + body2.deltaYAbs + PhysicsManager.OVERLAP_BIAS; - // If they did overlap (and can), figure out by how much and flip the corresponding flags - if(body1.deltaY > body2.deltaY) { - this._overlap = body1.bounds.bottom - body2.bounds.y; - if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.DOWN) || !(body2.allowCollisions & Phaser.Types.UP)) { - this._overlap = 0; - } else { - body1.touching |= Phaser.Types.DOWN; - body2.touching |= Phaser.Types.UP; - } - } else if(body1.deltaY < body2.deltaY) { - this._overlap = body1.bounds.y - body2.bounds.height - body2.bounds.y; - if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.UP) || !(body2.allowCollisions & Phaser.Types.DOWN)) { - this._overlap = 0; - } else { - body1.touching |= Phaser.Types.UP; - body2.touching |= Phaser.Types.DOWN; - } - } - } - } - // Then adjust their positions and velocities accordingly (if there was any overlap) - if(this._overlap != 0) { - this._obj1Velocity = body1.velocity.y; - this._obj2Velocity = body2.velocity.y; - /** - * Dynamic = gives and receives impacts - * Static = gives but doesn't receive impacts, cannot be moved by physics - * Kinematic = gives impacts, but never receives, can be moved by physics - */ - if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { - this._overlap *= 0.5; - body1.position.y = body1.position.y - this._overlap; - body2.position.y += this._overlap; - this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); - this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); - var average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; - this._obj1NewVelocity -= average; - this._obj2NewVelocity -= average; - body1.velocity.y = average + this._obj1NewVelocity * body1.bounce.y; - body2.velocity.y = average + this._obj2NewVelocity * body2.bounce.y; - } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { - this._overlap *= 2; - body1.position.y -= this._overlap; - body1.velocity.y = this._obj2Velocity - this._obj1Velocity * body1.bounce.y; - // This is special case code that handles things like horizontal moving platforms you can ride - //if (body2.parent.active && body2.moves && (body1.deltaY > body2.deltaY)) - if(body2.parent.active && (body1.deltaY > body2.deltaY)) { - body1.position.x += body2.position.x - body2.oldPosition.x; - } - } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { - this._overlap *= 2; - body2.position.y += this._overlap; - body2.velocity.y = this._obj1Velocity - this._obj2Velocity * body2.bounce.y; - // This is special case code that handles things like horizontal moving platforms you can ride - //if (object1.active && body1.moves && (body1.deltaY < body2.deltaY)) - if(body1.parent.active && (body1.deltaY < body2.deltaY)) { - body2.position.x += body1.position.x - body1.oldPosition.x; - } - } - return true; - } else { - return false; - } - }; - PhysicsManager.prototype.OLDseparate = function (shapeA, shapeB, distance, tangent) { - if(tangent.x == 1) { - console.log('1 The left side of ShapeA hit the right side of ShapeB', Math.floor(distance.x)); - shapeA.physics.touching |= Phaser.Types.LEFT; - shapeB.physics.touching |= Phaser.Types.RIGHT; - } else if(tangent.x == -1) { - console.log('2 The right side of ShapeA hit the left side of ShapeB', Math.floor(distance.x)); - shapeA.physics.touching |= Phaser.Types.RIGHT; - shapeB.physics.touching |= Phaser.Types.LEFT; - } - if(tangent.y == 1) { - console.log('3 The top of ShapeA hit the bottom of ShapeB', Math.floor(distance.y)); - shapeA.physics.touching |= Phaser.Types.UP; - shapeB.physics.touching |= Phaser.Types.DOWN; - } else if(tangent.y == -1) { - console.log('4 The bottom of ShapeA hit the top of ShapeB', Math.floor(distance.y)); - shapeA.physics.touching |= Phaser.Types.DOWN; - shapeB.physics.touching |= Phaser.Types.UP; - } - // only apply collision response forces if the object is travelling into, and not out of, the collision - var dot = Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent); - if(dot < 0) { - console.log('in to', dot); - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } else { - console.log('out of', dot); - } - shapeA.position.x += Math.floor(distance.x); - //shapeA.bounds.x += Math.floor(distance.x); - shapeA.position.y += Math.floor(distance.y); - //shapeA.bounds.y += distance.y; - console.log('------------------------------------------------'); - }; - PhysicsManager.prototype.collideWorld = function (shape) { - // Collide on the x-axis - this._distance.x = shape.world.bounds.x - (shape.position.x - shape.bounds.halfWidth); - if(0 < this._distance.x) { - // Hit Left - this._tangent.setTo(1, 0); - this.separateXWall(shape, this._distance, this._tangent); - } else { - this._distance.x = (shape.position.x + shape.bounds.halfWidth) - shape.world.bounds.right; - if(0 < this._distance.x) { - // Hit Right - this._tangent.setTo(-1, 0); - this._distance.reverse(); - this.separateXWall(shape, this._distance, this._tangent); - } - } - // Collide on the y-axis - this._distance.y = shape.world.bounds.y - (shape.position.y - shape.bounds.halfHeight); - if(0 < this._distance.y) { - // Hit Top - this._tangent.setTo(0, 1); - this.separateYWall(shape, this._distance, this._tangent); - } else { - this._distance.y = (shape.position.y + shape.bounds.halfHeight) - shape.world.bounds.bottom; - if(0 < this._distance.y) { - // Hit Bottom - this._tangent.setTo(0, -1); - this._distance.reverse(); - this.separateYWall(shape, this._distance, this._tangent); - } - } - }; - PhysicsManager.prototype.separateX = function (shapeA, shapeB, distance, tangent) { - if(tangent.x == 1) { - console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.LEFT; - shapeB.physics.touching |= Phaser.Types.RIGHT; - } else { - console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.RIGHT; - shapeB.physics.touching |= Phaser.Types.LEFT; - } - // collision edges - //shapeA.oH = tangent.x; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - } - shapeA.position.x += distance.x; - shapeA.bounds.x += distance.x; - }; - PhysicsManager.prototype.separateY = function (shapeA, shapeB, distance, tangent) { - if(tangent.y == 1) { - console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.UP; - shapeB.physics.touching |= Phaser.Types.DOWN; - } else { - console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.DOWN; - shapeB.physics.touching |= Phaser.Types.UP; - } - // collision edges - //shapeA.oV = tangent.y; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } - shapeA.position.y += distance.y; - shapeA.bounds.y += distance.y; - }; - PhysicsManager.prototype.separateXWall = function (shapeA, distance, tangent) { - if(tangent.x == 1) { - console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.LEFT; - } else { - console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); - shapeA.physics.touching |= Phaser.Types.RIGHT; - } - // collision edges - //shapeA.oH = tangent.x; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.x > 0) { - shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); - } else { - shapeA.physics.velocity.x = 0; - } - } - shapeA.position.x += distance.x; - }; - PhysicsManager.prototype.separateYWall = function (shapeA, distance, tangent) { - if(tangent.y == 1) { - console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.UP; - } else { - console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); - shapeA.physics.touching |= Phaser.Types.DOWN; - } - // collision edges - //shapeA.oV = tangent.y; - // only apply collision response forces if the object is travelling into, and not out of, the collision - if(Phaser.Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) { - // Apply horizontal bounce - if(shapeA.physics.bounce.y > 0) { - shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); - } else { - shapeA.physics.velocity.y = 0; - } - } - shapeA.position.y += distance.y; - }; - PhysicsManager.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; - }; - return PhysicsManager; - })(); - Physics.PhysicsManager = PhysicsManager; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /** - * Phaser - Physics - AABB - */ - (function (Physics) { - var AABB = (function () { - function AABB(game, sprite, x, y, width, height) { - this.game = game; - this.world = game.world.physics; - if(sprite !== null) { - this.sprite = sprite; - this.scale = Phaser.Vec2Utils.clone(this.sprite.scale); - } else { - this.sprite = null; - this.physics = null; - this.scale = new Phaser.Vec2(1, 1); - } - this.bounds = new Phaser.Rectangle(x + Math.round(width / 2), y + Math.round(height / 2), width, height); - this.position = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Phaser.Vec2(0, 0); - } - AABB.prototype.preUpdate = function () { - this.oldPosition.copyFrom(this.position); - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - if(this.sprite) { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - // Update scale / dimensions - if(Phaser.Vec2Utils.equals(this.scale, this.sprite.scale) == false) { - this.scale.copyFrom(this.sprite.scale); - this.bounds.width = this.sprite.width; - this.bounds.height = this.sprite.height; - } - } - }; - AABB.prototype.update = function () { - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - }; - AABB.prototype.setSize = function (width, height) { - this.bounds.width = width; - this.bounds.height = height; - }; - AABB.prototype.render = function (context) { - context.beginPath(); - context.strokeStyle = 'rgb(0,255,0)'; - context.strokeRect(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight, this.bounds.width, this.bounds.height); - context.stroke(); - context.closePath(); - // center point - context.fillStyle = 'rgb(0,255,0)'; - context.fillRect(this.position.x, this.position.y, 2, 2); - if(this.physics.touching & Phaser.Types.LEFT) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.RIGHT) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.UP) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - if(this.physics.touching & Phaser.Types.DOWN) { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - }; - Object.defineProperty(AABB.prototype, "hullWidth", { - get: function () { - if(this.deltaX > 0) { - return this.bounds.width + this.deltaX; - } else { - return this.bounds.width - this.deltaX; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullHeight", { - get: function () { - if(this.deltaY > 0) { - return this.bounds.height + this.deltaY; - } else { - return this.bounds.height - this.deltaY; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullX", { - get: function () { - if(this.position.x < this.oldPosition.x) { - return this.position.x; - } else { - return this.oldPosition.x; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "hullY", { - get: function () { - if(this.position.y < this.oldPosition.y) { - return this.position.y; - } else { - return this.oldPosition.y; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaXAbs", { - get: function () { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaYAbs", { - get: function () { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaX", { - get: function () { - return this.position.x - this.oldPosition.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(AABB.prototype, "deltaY", { - get: function () { - return this.position.y - this.oldPosition.y; - }, - enumerable: true, - configurable: true - }); - return AABB; - })(); - Physics.AABB = AABB; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /** - * Phaser - Physics - Circle - */ - (function (Physics) { - var Circle = (function () { - function Circle(game, sprite, x, y, diameter) { - this.game = game; - this.world = game.world.physics; - if(sprite !== null) { - this.sprite = sprite; - this.scale = Phaser.Vec2Utils.clone(this.sprite.scale); - } else { - this.sprite = null; - this.physics = null; - this.scale = new Phaser.Vec2(1, 1); - } - this.diameter = diameter; - this.radius = diameter / 2; - this.bounds = new Phaser.Rectangle(x + Math.round(diameter / 2), y + Math.round(diameter / 2), diameter, diameter); - this.position = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.oldPosition = new Phaser.Vec2(x + this.bounds.halfWidth, y + this.bounds.halfHeight); - this.offset = new Phaser.Vec2(0, 0); - } - Circle.prototype.preUpdate = function () { - this.oldPosition.copyFrom(this.position); - this.bounds.x = this.position.x - this.bounds.halfWidth; - this.bounds.y = this.position.y - this.bounds.halfHeight; - if(this.sprite) { - this.position.setTo((this.sprite.x + this.bounds.halfWidth) + this.offset.x, (this.sprite.y + this.bounds.halfHeight) + this.offset.y); - // Update scale / dimensions - if(Phaser.Vec2Utils.equals(this.scale, this.sprite.scale) == false) { - this.scale.copyFrom(this.sprite.scale); - // needs to be radius based (+ square) - //this.bounds.width = this.sprite.width; - //this.bounds.height = this.sprite.height; - } - } - }; - Circle.prototype.update = function () { - //this.bounds.x = this.position.x; - //this.bounds.y = this.position.y; - }; - Circle.prototype.setSize = function (width, height) { - this.bounds.width = width; - this.bounds.height = height; - }; - Circle.prototype.render = function (context) { - // center point - context.fillStyle = 'rgba(255,0,0,0.5)'; - context.arc(this.position.x, this.position.y, this.radius, 0, Math.PI * 2); - context.rect(this.position.x, this.position.y, 2, 2); - context.fill(); - /* - if (this.oH == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oH == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - - if (this.oV == 1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y - this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - else if (this.oV == -1) - { - context.beginPath(); - context.strokeStyle = 'rgb(255,0,0)'; - context.moveTo(this.position.x - this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.lineTo(this.position.x + this.bounds.halfWidth, this.position.y + this.bounds.halfHeight); - context.stroke(); - context.closePath(); - } - */ - }; - Object.defineProperty(Circle.prototype, "hullWidth", { - get: function () { - if(this.deltaX > 0) { - //return this.bounds.width + this.deltaX; - return this.diameter + this.deltaX; - } else { - //return this.bounds.width - this.deltaX; - return this.diameter - this.deltaX; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullHeight", { - get: function () { - if(this.deltaY > 0) { - //return this.bounds.height + this.deltaY; - return this.diameter + this.deltaY; - } else { - //return this.bounds.height - this.deltaY; - return this.diameter - this.deltaY; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullX", { - get: function () { - if(this.position.x < this.oldPosition.x) { - return this.position.x; - } else { - return this.oldPosition.x; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "hullY", { - get: function () { - if(this.position.y < this.oldPosition.y) { - return this.position.y; - } else { - return this.oldPosition.y; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaXAbs", { - get: function () { - return (this.deltaX > 0 ? this.deltaX : -this.deltaX); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaYAbs", { - get: function () { - return (this.deltaY > 0 ? this.deltaY : -this.deltaY); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaX", { - get: function () { - return this.position.x - this.oldPosition.x; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Circle.prototype, "deltaY", { - get: function () { - return this.position.y - this.oldPosition.y; - }, - enumerable: true, - configurable: true - }); - return Circle; - })(); - Physics.Circle = Circle; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - })(Phaser || (Phaser = {})); var Phaser; (function (Phaser) { /// /// /// - /// - /// - /// /** * Phaser - Physics - Body */ @@ -5422,6 +5818,7 @@ var Phaser; function () { // if this is all it does maybe move elsewhere? Sprite postUpdate? if(this.type !== Phaser.Types.BODY_DISABLED) { + this.game.world.physics.updateMotion(this); this.parent.x = (this.position.x - this.bounds.halfWidth) - this.offset.x; this.parent.y = (this.position.y - this.bounds.halfHeight) - this.offset.y; this.wasTouching = this.touching; @@ -5554,7 +5951,7 @@ var Phaser; this.parent.texture.context.fillStyle = color; this.parent.texture.context.fillText('Sprite: (' + this.parent.frameBounds.width + ' x ' + this.parent.frameBounds.height + ')', x, y); //this.parent.texture.context.fillText('x: ' + this._parent.frameBounds.x.toFixed(1) + ' y: ' + this._parent.frameBounds.y.toFixed(1) + ' rotation: ' + this._parent.rotation.toFixed(1), x, y + 14); - this.parent.texture.context.fillText('x: ' + this.shape.bounds.x.toFixed(1) + ' y: ' + this.shape.bounds.y.toFixed(1) + ' rotation: ' + this._parent.rotation.toFixed(1), x, y + 14); + this.parent.texture.context.fillText('x: ' + this.bounds.x.toFixed(1) + ' y: ' + this.bounds.y.toFixed(1) + ' angle: ' + this.angle.toFixed(1), x, y + 14); this.parent.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); this.parent.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); }; @@ -5569,7 +5966,6 @@ var Phaser; /// /// /// -/// /// /** * Phaser - Sprite @@ -5587,7 +5983,6 @@ var Phaser; * @param [key] {string} Key of the graphic you want to load for this sprite. * @param [bodyType] {number} The physics body type of the object (defaults to BODY_DISABLED) */ - //constructor(game: Game, x?: number = 0, y?: number = 0, key?: string = null, width?: number = 16, height?: number = 16) { function Sprite(game, x, y, key, bodyType) { if (typeof x === "undefined") { x = 0; } if (typeof y === "undefined") { y = 0; } @@ -5632,6 +6027,7 @@ var Phaser; ; this.animations = new Phaser.Components.AnimationManager(this); this.texture = new Phaser.Components.Texture(this, key); + this.cameraBlacklist = []; // Transform related (if we add any more then move to a component) this.origin = new Phaser.Vec2(0, 0); this.scale = new Phaser.Vec2(1, 1); @@ -5714,7 +6110,7 @@ var Phaser; function () { this.frameBounds.x = this.x; this.frameBounds.y = this.y; - if(this.modified == false && (!this.scale.equals(1) || !this.skew.equals(0) || this.rotation != 0 || this.rotationOffset != 0 || this.texture.flippedX || this.texture.flippedY)) { + if(this.modified == false && (!this.scale.equals(1) || !this.skew.equals(0) || this.angle != 0 || this.angleOffset != 0 || this.texture.flippedX || this.texture.flippedY)) { this.modified = true; } }; @@ -5729,7 +6125,6 @@ var Phaser; function () { this.animations.update(); this.body.postUpdate(); - //this.physics.update(); /* if (this.worldBounds != null) { @@ -5768,7 +6163,7 @@ var Phaser; } */ - if(this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.rotation == 0 && this.rotationOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) { + if(this.modified == true && this.scale.equals(1) && this.skew.equals(0) && this.angle == 0 && this.angleOffset == 0 && this.texture.flippedX == false && this.texture.flippedY == false) { this.modified = false; } }; @@ -5777,6 +6172,25 @@ var Phaser; */ function () { }; + Sprite.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; + }; + Sprite.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; + }; return Sprite; })(); Phaser.Sprite = Sprite; @@ -7132,8 +7546,1522 @@ var Phaser; Phaser.Tween = Tween; })(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.body.touching) { + if(this.body.angularVelocity != 0) { + this.body.angularVelocity = -this.body.angularVelocity; + } + } + if(this.body.acceleration.y > 0)//special behavior for particles with gravity + { + if(this.body.touching & Phaser.Types.FLOOR) { + this.body.drag.x = this.friction; + if(!(this.body.wasTouching & Phaser.Types.FLOOR)) { + if(this.body.velocity.y < -this.body.bounce.y * 10) { + if(this.body.angularVelocity != 0) { + this.body.angularVelocity *= -this.body.bounce.y; + } + } else { + this.body.velocity.y = 0; + this.body.angularVelocity = 0; + } + } + } else { + this.body.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 - Emitter +* +* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for +* continuous effects like rain and fire. All it really does is launch Particle objects out +* at set intervals, and fixes their positions and velocities accorindgly. +*/ +var Phaser; +(function (Phaser) { + var Emitter = (function (_super) { + __extends(Emitter, _super); + /** + * Creates a new Emitter object at a specific position. + * Does NOT automatically generate or attach particles! + * + * @param x {number} The X position of the emitter. + * @param y {number} The Y position of the emitter. + * @param [size] {number} Specifies a maximum capacity for this emitter. + */ + function Emitter(game, x, y, size) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof size === "undefined") { size = 0; } + _super.call(this, game, size); + this.x = x; + this.y = y; + this.width = 0; + this.height = 0; + this.minParticleSpeed = new Phaser.Vec2(-100, -100); + this.maxParticleSpeed = new Phaser.Vec2(100, 100); + this.minRotation = -360; + this.maxRotation = 360; + this.gravity = 0; + this.particleClass = null; + this.particleDrag = new Phaser.Vec2(); + this.frequency = 0.1; + this.lifespan = 3; + this.bounce = 0; + this._quantity = 0; + this._counter = 0; + this._explode = true; + this.on = false; + } + 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.texture.loadImage(graphics); + } + } + if(collide > 0) { + particle.body.allowCollisions = Phaser.Types.ANY; + particle.body.type = Phaser.Types.BODY_DYNAMIC; + particle.width *= collide; + particle.height *= collide; + } else { + particle.body.allowCollisions = Phaser.Types.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; + this.alive = false; + this.exists = false; + }; + Emitter.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; + }; + 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.body.bounce.setTo(this.bounce, this.bounce); + Phaser.SpriteUtils.reset(particle, 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.body.velocity.x = this.minParticleSpeed.x + this.game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x); + } else { + particle.body.velocity.x = this.minParticleSpeed.x; + } + if(this.minParticleSpeed.y != this.maxParticleSpeed.y) { + particle.body.velocity.y = this.minParticleSpeed.y + this.game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y); + } else { + particle.body.velocity.y = this.minParticleSpeed.y; + } + particle.body.acceleration.y = this.gravity; + if(this.minRotation != this.maxRotation && this.minRotation !== 0 && this.maxRotation !== 0) { + particle.body.angularVelocity = this.minRotation + this.game.math.random() * (this.maxRotation - this.minRotation); + } else { + particle.body.angularVelocity = this.minRotation; + } + if(particle.body.angularVelocity != 0) { + particle.angle = this.game.math.random() * 360 - 180; + } + particle.body.drag.x = this.particleDrag.x; + particle.body.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) { + this.x = object.body.bounds.halfWidth - (this.width >> 1); + this.y = object.body.bounds.halfHeight - (this.height >> 1); + }; + return Emitter; + })(Phaser.Group); + Phaser.Emitter = Emitter; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - ScrollRegion +* +* Creates a scrolling region within a ScrollZone. +* It is scrolled via the scrollSpeed.x/y properties. +*/ +var Phaser; +(function (Phaser) { + var ScrollRegion = (function () { + /** + * ScrollRegion constructor + * Create a new ScrollRegion. + * + * @param x {number} X position in world coordinate. + * @param y {number} Y position in world coordinate. + * @param width {number} Width of this object. + * @param height {number} Height of this object. + * @param speedX {number} X-axis scrolling speed. + * @param speedY {number} Y-axis scrolling speed. + */ + function ScrollRegion(x, y, width, height, speedX, speedY) { + this._anchorWidth = 0; + this._anchorHeight = 0; + this._inverseWidth = 0; + this._inverseHeight = 0; + /** + * Will this region be rendered? (default to true) + * @type {boolean} + */ + this.visible = true; + // Our seamless scrolling quads + this._A = new Phaser.Rectangle(x, y, width, height); + this._B = new Phaser.Rectangle(x, y, width, height); + this._C = new Phaser.Rectangle(x, y, width, height); + this._D = new Phaser.Rectangle(x, y, width, height); + this._scroll = new Phaser.Vec2(); + this._bounds = new Phaser.Rectangle(x, y, width, height); + this.scrollSpeed = new Phaser.Vec2(speedX, speedY); + } + ScrollRegion.prototype.update = /** + * Update region scrolling with tick time. + * @param delta {number} Elapsed time since last update. + */ + function (delta) { + this._scroll.x += this.scrollSpeed.x; + this._scroll.y += this.scrollSpeed.y; + if(this._scroll.x > this._bounds.right) { + this._scroll.x = this._bounds.x; + } + if(this._scroll.x < this._bounds.x) { + this._scroll.x = this._bounds.right; + } + if(this._scroll.y > this._bounds.bottom) { + this._scroll.y = this._bounds.y; + } + if(this._scroll.y < this._bounds.y) { + this._scroll.y = this._bounds.bottom; + } + // Anchor Dimensions + this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; + this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; + if(this._anchorWidth > this._bounds.width) { + this._anchorWidth = this._bounds.width; + } + if(this._anchorHeight > this._bounds.height) { + this._anchorHeight = this._bounds.height; + } + this._inverseWidth = this._bounds.width - this._anchorWidth; + this._inverseHeight = this._bounds.height - this._anchorHeight; + // Rectangle A + this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); + // Rectangle B + this._B.y = this._scroll.y; + this._B.width = this._inverseWidth; + this._B.height = this._anchorHeight; + // Rectangle C + this._C.x = this._scroll.x; + this._C.width = this._anchorWidth; + this._C.height = this._inverseHeight; + // Rectangle D + this._D.width = this._inverseWidth; + this._D.height = this._inverseHeight; + }; + ScrollRegion.prototype.render = /** + * Render this region to specific context. + * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. + * @param texture {object} The texture to be rendered. + * @param dx {number} X position in world coordinate. + * @param dy {number} Y position in world coordinate. + * @param width {number} Width of this region to be rendered. + * @param height {number} Height of this region to be rendered. + */ + function (context, texture, dx, dy, dw, dh) { + if(this.visible == false) { + return; + } + // dx/dy are the world coordinates to render the FULL ScrollZone into. + // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. + this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); + this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); + this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); + this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); + //context.fillStyle = 'rgb(255,255,255)'; + //context.font = '18px Arial'; + //context.fillText('RectangleA: ' + this._A.toString(), 32, 450); + //context.fillText('RectangleB: ' + this._B.toString(), 32, 480); + //context.fillText('RectangleC: ' + this._C.toString(), 32, 510); + //context.fillText('RectangleD: ' + this._D.toString(), 32, 540); + }; + ScrollRegion.prototype.crop = /** + * Crop part of the texture and render it to the given context. + * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. + * @param texture {object} Texture to be rendered. + * @param srcX {number} Target region top-left x coordinate in the texture. + * @param srcX {number} Target region top-left y coordinate in the texture. + * @param srcW {number} Target region width in the texture. + * @param srcH {number} Target region height in the texture. + * @param destX {number} Render region top-left x coordinate in the context. + * @param destX {number} Render region top-left y coordinate in the context. + * @param destW {number} Target region width in the context. + * @param destH {number} Target region height in the context. + * @param offsetX {number} X offset to the context. + * @param offsetY {number} Y offset to the context. + */ + function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { + offsetX += destX; + offsetY += destY; + if(srcW > (destX + destW) - offsetX) { + srcW = (destX + destW) - offsetX; + } + if(srcH > (destY + destH) - offsetY) { + srcH = (destY + destH) - offsetY; + } + srcX = Math.floor(srcX); + srcY = Math.floor(srcY); + srcW = Math.floor(srcW); + srcH = Math.floor(srcH); + offsetX = Math.floor(offsetX + this._bounds.x); + offsetY = Math.floor(offsetY + this._bounds.y); + if(srcW > 0 && srcH > 0) { + context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); + } + }; + return ScrollRegion; + })(); + Phaser.ScrollRegion = ScrollRegion; +})(Phaser || (Phaser = {})); +/// +/// +/// +/** +* Phaser - 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, key); + this.type = Phaser.Types.SCROLLZONE; + this.render = game.renderer.renderScrollZone; + this.regions = []; + if(this.texture.loaded) { + if(width > this.width || height > this.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.width || height < this.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.createRepeatingTexture = /** + * Create repeating texture with _texture, and store it into the _dynamicTexture. + * Used to create texture when texture image is small than size of the zone. + */ + function (regionWidth, regionHeight) { + // Work out how many we'll need of the source image to make it tile properly + var tileWidth = Math.ceil(this.width / regionWidth) * regionWidth; + var tileHeight = Math.ceil(this.height / regionHeight) * regionHeight; + var dt = new Phaser.DynamicTexture(this.game, tileWidth, tileHeight); + dt.context.rect(0, 0, tileWidth, tileHeight); + dt.context.fillStyle = dt.context.createPattern(this.texture.imageTexture, "repeat"); + dt.context.fill(); + this.texture.loadDynamicTexture(dt); + }; + return ScrollZone; + })(Phaser.Sprite); + Phaser.ScrollZone = ScrollZone; +})(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.body.bounds.x < 0 || object.body.bounds.x > this.widthInPixels || object.body.bounds.y < 0 || object.body.bounds.bottom > this.heightInPixels) { + return; + } + // What tiles do we need to check against? + this._tempTileX = this._game.math.snapToFloor(object.body.bounds.x, this.tileWidth) / this.tileWidth; + this._tempTileY = this._game.math.snapToFloor(object.body.bounds.y, this.tileHeight) / this.tileHeight; + this._tempTileW = (this._game.math.snapToCeil(object.body.bounds.width, this.tileWidth) + this.tileWidth) / this.tileWidth; + this._tempTileH = (this._game.math.snapToCeil(object.body.bounds.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.Physics.PhysicsManager.TILE_OVERLAP = false; + for(var r = 0; r < this._tempTileBlock.length; r++) { + if(this._game.world.physics.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.Types.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 = Phaser.Types.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.Types.ANY) { + this.collideLeft = true; + this.collideRight = true; + this.collideUp = true; + this.collideDown = true; + return; + } + if(collision & Phaser.Types.LEFT || collision & Phaser.Types.WALL) { + this.collideLeft = true; + } + if(collision & Phaser.Types.RIGHT || collision & Phaser.Types.WALL) { + this.collideRight = true; + } + if(collision & Phaser.Types.UP || collision & Phaser.Types.CEILING) { + this.collideUp = true; + } + if(collision & Phaser.Types.DOWN || collision & Phaser.Types.CEILING) { + this.collideDown = true; + } + }; + Tile.prototype.resetCollision = /** + * Reset collision status flags. + */ + function () { + this.allowCollisions = Phaser.Types.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 () { + /** + * 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; } + /** + * Tilemap collision callback. + * @type {function} + */ + this.collisionCallback = null; + this.game = game; + this.type = Phaser.Types.TILEMAP; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; + this.tiles = []; + this.layers = []; + this.cameraBlacklist = []; + this.mapFormat = format; + switch(format) { + case Tilemap.FORMAT_CSV: + this.parseCSV(game.cache.getText(mapData), key, tileWidth, tileHeight); + break; + case Tilemap.FORMAT_TILED_JSON: + this.parseTiledJSON(game.cache.getText(mapData), key); + break; + } + if(this.currentLayer && resizeWorld) { + this.game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); + } + } + Tilemap.FORMAT_CSV = 0; + Tilemap.FORMAT_TILED_JSON = 1; + Tilemap.prototype.update = /** + * Inherited update method. + */ + function () { + }; + Tilemap.prototype.render = /** + * Render this tilemap to a specific camera with specific offset. + * @param camera {Camera} The camera this tilemap will be rendered to. + * @param cameraOffsetX {number} X offset of the camera. + * @param cameraOffsetY {number} Y offset of the camera. + */ + function (camera, cameraOffsetX, cameraOffsetY) { + if(this.cameraBlacklist.indexOf(camera.ID) == -1) { + // Loop through the layers + for(var i = 0; i < this.layers.length; i++) { + this.layers[i].render(camera, cameraOffsetX, cameraOffsetY); + } + } + }; + Tilemap.prototype.parseCSV = /** + * Parset csv map data and generate tiles. + * @param data {string} CSV map data. + * @param key {string} Asset key for tileset image. + * @param tileWidth {number} Width of its tile. + * @param tileHeight {number} Height of its tile. + */ + function (data, key, tileWidth, tileHeight) { + var layer = new Phaser.TilemapLayer(this.game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); + // Trim any rogue whitespace from the data + data = data.trim(); + var rows = data.split("\n"); + for(var i = 0; i < rows.length; i++) { + var column = rows[i].split(","); + if(column.length > 0) { + layer.addColumn(column); + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.parseTiledJSON = /** + * Parset JSON map data and generate tiles. + * @param data {string} JSON map data. + * @param key {string} Asset key for tileset image. + */ + function (data, key) { + // Trim any rogue whitespace from the data + data = data.trim(); + var json = JSON.parse(data); + for(var i = 0; i < json.layers.length; i++) { + var layer = new Phaser.TilemapLayer(this.game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); + layer.alpha = json.layers[i].opacity; + layer.visible = json.layers[i].visible; + layer.tileMargin = json.tilesets[0].margin; + layer.tileSpacing = json.tilesets[0].spacing; + var c = 0; + var row; + for(var t = 0; t < json.layers[i].data.length; t++) { + if(c == 0) { + row = []; + } + row.push(json.layers[i].data[t]); + c++; + if(c == json.layers[i].width) { + layer.addColumn(row); + c = 0; + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + } + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.generateTiles = /** + * Create tiles of given quantity. + * @param qty {number} Quentity of tiles to be generated. + */ + function (qty) { + for(var i = 0; i < qty; i++) { + this.tiles.push(new Phaser.Tile(this.game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); + } + }; + Object.defineProperty(Tilemap.prototype, "widthInPixels", { + get: function () { + return this.currentLayer.widthInPixels; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tilemap.prototype, "heightInPixels", { + get: function () { + return this.currentLayer.heightInPixels; + }, + enumerable: true, + configurable: true + }); + Tilemap.prototype.setCollisionCallback = // Tile Collision + /** + * Set callback to be called when this tilemap collides. + * @param context {object} Callback will be called with this context. + * @param callback {function} Callback function. + */ + function (context, callback) { + this.collisionCallbackContext = context; + this.collisionCallback = callback; + }; + Tilemap.prototype.setCollisionRange = /** + * Set collision configs of tiles in a range index. + * @param start {number} First index of tiles. + * @param end {number} Last index of tiles. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + function (start, end, collision, resetCollisions, separateX, separateY) { + if (typeof collision === "undefined") { collision = Phaser.Types.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.Types.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.body.type == Phaser.Types.BODY_DYNAMIC && object.exists == true && object.body.allowCollisions != Phaser.Types.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.Tilemap = Tilemap; + // Set current layer + // Set layer order? + // Delete tiles of certain type + // Erase tiles + })(Phaser || (Phaser = {})); +/// /// -/// +/// +/// +/// +/// +/// +/// /** * Phaser - GameObjectFactory * @@ -7206,27 +9134,15 @@ var Phaser; if (typeof maxSize === "undefined") { maxSize = 0; } return this._world.group.add(new Phaser.Group(this._game, maxSize)); }; - GameObjectFactory.prototype.physicsAABB = /** - * 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} Optional, key for the sprite sheet you want it to use. - * @returns {Sprite} The newly created sprite object. - * WILL NEED TO TRACK A SPRITE - */ - function (x, y, width, height) { - return this._world.physics.add(new Phaser.Physics.AABB(this._game, null, x, y, width, height)); - }; - GameObjectFactory.prototype.scrollZone = /** + GameObjectFactory.prototype.particle = /** * Create a new Particle. * * @return {Particle} The newly created particle object. */ - //public particle(): Particle { - // return new Particle(this._game); - //} - /** + function () { + return new Phaser.Particle(this._game); + }; + GameObjectFactory.prototype.emitter = /** * Create a new Emitter. * * @param x {number} Optional, x position of the emitter. @@ -7234,10 +9150,13 @@ var 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.group.add(new Emitter(this._game, x, y, size)); - //} - /** + 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.group.add(new Phaser.Emitter(this._game, x, y, size)); + }; + GameObjectFactory.prototype.scrollZone = /** * Create a new ScrollZone object with image key, position and size. * * @param key {string} Key to a image you wish this object to use. @@ -7254,7 +9173,7 @@ var Phaser; if (typeof height === "undefined") { height = 0; } return this._world.group.add(new Phaser.ScrollZone(this._game, key, x, y, width, height)); }; - GameObjectFactory.prototype.tween = /** + GameObjectFactory.prototype.tilemap = /** * Create a new Tilemap. * * @param key {string} Key for tileset image. @@ -7265,10 +9184,13 @@ var Phaser; * @param [tileHeight] {number} height of each tile. * @return {Tilemap} The newly created tilemap object. */ - //public tilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap { - // return this._world.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); - //} - /** + function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { + if (typeof resizeWorld === "undefined") { resizeWorld = true; } + if (typeof tileWidth === "undefined") { tileWidth = 0; } + if (typeof tileHeight === "undefined") { tileHeight = 0; } + return this._world.group.add(new Phaser.Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight)); + }; + GameObjectFactory.prototype.tween = /** * Create a tween object for a specific object. * * @param obj Object you wish the tween will affect. @@ -7287,7 +9209,7 @@ var Phaser; function (sprite) { return this._world.group.add(sprite); }; - GameObjectFactory.prototype.existingScrollZone = /** + GameObjectFactory.prototype.existingEmitter = /** * 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. * @@ -7304,10 +9226,10 @@ var 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); - //} - /** + function (emitter) { + return this._world.group.add(emitter); + }; + GameObjectFactory.prototype.existingScrollZone = /** * 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. * @@ -7317,17 +9239,17 @@ var Phaser; function (scrollZone) { return this._world.group.add(scrollZone); }; - GameObjectFactory.prototype.existingTween = /** + GameObjectFactory.prototype.existingTilemap = /** * Add an existing Tilemap to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * * @param tilemap The Tilemap to add to the Game World * @return {Phaser.Tilemap} The Tilemap object */ - //public existingTilemap(tilemap: Tilemap): Tilemap { - // return this._world.group.add(tilemap); - //} - /** + function (tilemap) { + return this._world.group.add(tilemap); + }; + GameObjectFactory.prototype.existingTween = /** * Add an existing Tween to the current world. * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. * @@ -7341,954 +9263,6 @@ 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; - Types.BODY_DISABLED = 0; - Types.BODY_DYNAMIC = 1; - Types.BODY_STATIC = 2; - Types.BODY_KINEMATIC = 3; - Types.LEFT = 0x0001; - Types.RIGHT = 0x0010; - Types.UP = 0x0100; - Types.DOWN = 0x1000; - Types.NONE = 0; - Types.CEILING = Types.UP; - Types.FLOOR = Types.DOWN; - Types.WALL = Types.LEFT | Types.RIGHT; - Types.ANY = Types.LEFT | Types.RIGHT | Types.UP | Types.DOWN; - return Types; - })(); - Phaser.Types = Types; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - Group -* -* This class is used for organising, updating and sorting game objects. -*/ -var Phaser; -(function (Phaser) { - 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. - * If this value is set it will call a canvas context save and restore before and after the render pass. - * Set to null to disable. - */ - this.globalCompositeOperation = null; - /** - * You can set an alpha value on this Group that will be applied before the render method is called on this Groups children. - * This is useful if you wish to alpha a whole group of children as it saves doing it one-by-one. - * Set to 0 to disable. - */ - this.alpha = 0; - this.game = game; - this.type = Phaser.Types.GROUP; - this.exists = true; - this.visible = true; - this.members = []; - this.length = 0; - this._maxSize = maxSize; - this._marker = 0; - this._sortIndex = null; - this.cameraBlacklist = []; - } - Group.ASCENDING = -1; - Group.DESCENDING = 1; - 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) { - 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; - } - this._sortIndex = null; - }; - Group.prototype.update = /** - * 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; } - 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 = /** - * 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 (renderer, camera) { - if(camera.isHidden(this) == true) { - return; - } - if(this.globalCompositeOperation) { - this.game.stage.context.save(); - this.game.stage.context.globalCompositeOperation = this.globalCompositeOperation; - } - if(this.alpha > 0) { - this._prevAlpha = this.game.stage.context.globalAlpha; - this.game.stage.context.globalAlpha = this.alpha; - } - 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.call(renderer, camera, this._member); - } - } - if(this.alpha > 0) { - this.game.stage.context.globalAlpha = this._prevAlpha; - } - if(this.globalCompositeOperation) { - this.game.stage.context.restore(); - } - }; - Object.defineProperty(Group.prototype, "maxSize", { - get: /** - * The maximum capacity of this group. Default is 0, meaning no max capacity, and the group can just grow. - */ - function () { - return this._maxSize; - }, - set: /** - * @private - */ - function (Size) { - this._maxSize = Size; - if(this._marker >= this._maxSize) { - this._marker = 0; - } - 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 - 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; - }, - enumerable: true, - configurable: true - }); - Group.prototype.add = /** - * Adds a new Basic subclass (Basic, GameObject, Sprite, etc) to the group. - * Group will try to replace a null member of the array first. - * Failing that, Group will add it to the end of the member array, - * assuming there is room for it, and doubling the size of the array if necessary. - * - *

WARNING: If the group has a maxSize that has already been met, - * the object will NOT be added to the group!

- * - * @param {Basic} Object The object you want to add to the group. - * @return {Basic} The same Basic object that was passed in. - */ - function (object) { - //Don't bother adding an object twice. - if(this.members.indexOf(Object) >= 0) { - return object; - } - //First, look for a null entry where we can add the object. - 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; - } - 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; - } else if(this.members.length * 2 <= this._maxSize) { - this.members.length *= 2; - } else { - this.members.length = this._maxSize; - } - } else { - this.members.length *= 2; - } - //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[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. - * - *

If you specified a maximum size for this group (like in Emitter), - * then recycle will employ what we're calling "rotating" recycling. - * Recycle() will first check to see if the group is at capacity yet. - * If group is not yet at capacity, recycle() returns a new object. - * If the group IS at capacity, then recycle() just returns the next object in line.

- * - *

If you did NOT specify a maximum size for this group, - * then recycle() will employ what we're calling "grow-style" recycling. - * Recycle() will return either the first object with exists == false, - * or, finding none, add a new object to the array, - * doubling the size of the array if necessary.

- * - *

WARNING: If this function needs to create a new object, - * and no object class was provided, it will return null - * instead of a valid object!

- * - * @param {class} ObjectClass The class type you want to recycle (e.g. Basic, EvilRobot, etc). Do NOT "new" the class in the parameter! - * - * @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; } - if(this._maxSize > 0) { - if(this.length < this._maxSize) { - if(objectClass == null) { - return null; - } - return this.add(new objectClass(this.game)); - } else { - this._member = this.members[this._marker++]; - if(this._marker >= this._maxSize) { - this._marker = 0; - } - return this._member; - } - } else { - this._member = this.getFirstAvailable(objectClass); - if(this._member != null) { - return this._member; - } - if(objectClass == null) { - return null; - } - return this.add(new objectClass(this.game)); - } - }; - Group.prototype.remove = /** - * Removes an object from the group. - * - * @param {Basic} object The Basic you want to remove. - * @param {boolean} splice Whether the object should be cut from the array entirely or not. - * - * @return {Basic} The removed object. - */ - function (object, splice) { - if (typeof splice === "undefined") { splice = false; } - this._i = this.members.indexOf(object); - if(this._i < 0 || (this._i >= this.members.length)) { - return null; - } - if(splice) { - this.members.splice(this._i, 1); - this.length--; - } else { - this.members[this._i] = null; - } - return object; - }; - Group.prototype.replace = /** - * Replaces an existing Basic with a new one. - * - * @param {Basic} oldObject The object you want to replace. - * @param {Basic} newObject The new object you want to use instead. - * - * @return {Basic} The new object. - */ - function (oldObject, newObject) { - this._i = this.members.indexOf(oldObject); - if(this._i < 0 || (this._i >= this.members.length)) { - return null; - } - this.members[this._i] = newObject; - return newObject; - }; - Group.prototype.sort = /** - * Call this function to sort the group according to a particular value and order. - * For example, to sort game objects for Zelda-style overlaps you might call - * myGroup.sort("y",Group.ASCENDING) at the bottom of your - * State.update() override. To sort all existing objects after - * a big explosion or bomb attack, you might call myGroup.sort("exists",Group.DESCENDING). - * - * @param {string} index The string name of the member variable you want to sort on. Default value is "y". - * @param {number} order A Group constant that defines the sort order. Possible values are Group.ASCENDING and Group.DESCENDING. Default value is Group.ASCENDING. - */ - function (index, order) { - if (typeof index === "undefined") { index = "y"; } - if (typeof order === "undefined") { order = Group.ASCENDING; } - this._sortIndex = index; - this._sortOrder = order; - this.members.sort(this.sortHandler); - }; - Group.prototype.setAll = /** - * Go through and set the specified variable to the specified value on all members of the group. - * - * @param {string} VariableName The string representation of the variable name you want to modify, for example "visible" or "scrollFactor". - * @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; } - 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 { - this._member[variableName] = value; - } - } - } - }; - Group.prototype.callAll = /** - * Go through and call the specified function on all members of the group. - * Currently only works on functions that have no required parameters. - * - * @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; } - 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 { - this._member[functionName](); - } - } - } - }; - Group.prototype.forEach = /** - * @param {function} callback - * @param {boolean} recursive - */ - function (callback, recursive) { - if (typeof recursive === "undefined") { recursive = false; } - 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, this._member); - } - } - } - }; - Group.prototype.forEachAlive = /** - * @param {any} context - * @param {function} callback - * @param {boolean} recursive - */ - function (context, callback, recursive) { - if (typeof recursive === "undefined") { recursive = false; } - 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, this._member); - } - } - } - }; - Group.prototype.getFirstAvailable = /** - * Call this function to retrieve the first object with exists == false in the group. - * This is handy for recycling in general, e.g. respawning enemies. - * - * @param {any} [ObjectClass] An optional parameter that lets you narrow the results to instances of this particular class. - * - * @return {any} A Basic currently flagged as not existing. - */ - 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; - }; - Group.prototype.getFirstNull = /** - * Call this function to retrieve the first index set to 'null'. - * Returns -1 if no index stores a null object. - * - * @return {number} An int indicating the first null slot in the group. - */ - function () { - this._i = 0; - while(this._i < this.length) { - if(this.members[this._i] == null) { - return this._i; - } else { - this._i++; - } - } - return -1; - }; - Group.prototype.getFirstExtant = /** - * Call this function to retrieve the first object with exists == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as existing. - */ - function () { - 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; - }; - Group.prototype.getFirstAlive = /** - * Call this function to retrieve the first object with dead == false in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as not dead. - */ - function () { - 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; - }; - Group.prototype.getFirstDead = /** - * Call this function to retrieve the first object with dead == true in the group. - * This is handy for checking if everything's wiped out, or choosing a squad leader, etc. - * - * @return {Basic} A Basic currently flagged as dead. - */ - function () { - 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; - }; - Group.prototype.countLiving = /** - * Call this function to find out how many members of the group are not dead. - * - * @return {number} The number of Basics flagged as not dead. Returns -1 if group is empty. - */ - function () { - 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(this._member.exists && this._member.alive) { - this._count++; - } - } - } - return this._count; - }; - Group.prototype.countDead = /** - * Call this function to find out how many members of the group are dead. - * - * @return {number} The number of Basics flagged as dead. Returns -1 if group is empty. - */ - function () { - 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(!this._member.alive) { - this._count++; - } - } - } - return this._count; - }; - Group.prototype.getRandom = /** - * Returns a member at random from the group. - * - * @param {number} StartIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} Length Optional restriction on the number of values you want to randomly select from. - * - * @return {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; - } - return this.game.math.getRandom(this.members, startIndex, length); - }; - Group.prototype.clear = /** - * Remove all instances of Basic subclass (Basic, Block, etc) from the list. - * WARNING: does not destroy() or kill() any of these objects! - */ - function () { - this.length = this.members.length = 0; - }; - Group.prototype.kill = /** - * Calls kill on the group's members and then on the group itself. - */ - function () { - this._i = 0; - while(this._i < this.length) { - this._member = this.members[this._i++]; - if((this._member != null) && this._member.exists) { - this._member.kill(); - } - } - }; - Group.prototype.sortHandler = /** - * Helper function for the sort process. - * - * @param {Basic} Obj1 The first object being sorted. - * @param {Basic} Obj2 The second object being sorted. - * - * @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]) { - return this._sortOrder; - } else if(obj1[this._sortIndex] > obj2[this._sortIndex]) { - return -this._sortOrder; - } - return 0; - }; - return Group; - })(); - Phaser.Group = Group; -})(Phaser || (Phaser = {})); -/// -/** -* Phaser - SignalBinding -* -* An object that represents a binding between a Signal and a listener function. -* Based on JS Signals by Miller Medeiros. Converted by TypeScript by Richard Davey. -* Released under the MIT license -* http://millermedeiros.github.com/js-signals/ -*/ -var Phaser; -(function (Phaser) { - var SignalBinding = (function () { - /** - * Object that represents a binding between a Signal and a listener function. - *
- This is an internal constructor and shouldn't be called by regular users. - *
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. - * @author Miller Medeiros - * @constructor - * @internal - * @name SignalBinding - * @param {Signal} signal Reference to Signal object that listener is currently bound to. - * @param {Function} listener Handler function bound to the signal. - * @param {boolean} isOnce If binding should be executed just once. - * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {Number} [priority] The priority level of the event listener. (default = 0). - */ - function SignalBinding(signal, listener, isOnce, listenerContext, priority) { - if (typeof priority === "undefined") { priority = 0; } - /** - * If binding is active and should be executed. - * @type boolean - */ - this.active = true; - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters) - * @type Array|null - */ - this.params = null; - this._listener = listener; - this._isOnce = isOnce; - this.context = listenerContext; - this._signal = signal; - this.priority = priority || 0; - } - SignalBinding.prototype.execute = /** - * Call listener passing arbitrary parameters. - *

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

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

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

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

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

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

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

- */ - function () { - this.removeAll(); - delete this._bindings; - delete this._prevParams; - }; - Signal.prototype.toString = /** - * @return {string} String representation of the object. - */ - function () { - return '[Signal active:' + this.active + ' numListeners:' + this.getNumListeners() + ']'; - }; - return Signal; - })(); - Phaser.Signal = Signal; -})(Phaser || (Phaser = {})); /// /// /** @@ -9431,6 +10405,1111 @@ var Phaser; })(); Phaser.TweenManager = TweenManager; })(Phaser || (Phaser = {})); +/// +/// +/// +/// +/** +* Phaser - CircleUtils +* +* A collection of methods useful for manipulating and comparing Circle objects. +* +* TODO: +*/ +var Phaser; +(function (Phaser) { + var CircleUtils = (function () { + function CircleUtils() { } + CircleUtils.clone = /** + * Returns a new Circle object with the same values for the x, y, width, and height properties as the original Circle object. + * @method clone + * @param {Circle} a - The Circle object. + * @param {Circle} [optional] out Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. + * @return {Phaser.Circle} + **/ + function clone(a, out) { + if (typeof out === "undefined") { out = new Phaser.Circle(); } + return out.setTo(a.x, a.y, a.diameter); + }; + CircleUtils.contains = /** + * Return true if the given x/y coordinates are within the Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method contains + * @param {Circle} a - The Circle object. + * @param {Number} The X value of the coordinate to test. + * @param {Number} The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function contains(a, x, y) { + //return (a.radius * a.radius >= Collision.distanceSquared(a.x, a.y, x, y)); + return true; + }; + CircleUtils.containsPoint = /** + * Return true if the coordinates of the given Point object are within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleContainsPoint instead. + * @method containsPoint + * @param {Circle} a - The Circle object. + * @param {Point} The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsPoint(a, point) { + return CircleUtils.contains(a, point.x, point.y); + }; + CircleUtils.containsCircle = /** + * Return true if the given Circle is contained entirely within this Circle object. + * If you need details about the intersection then use Phaser.Intersect.circleToCircle instead. + * @method containsCircle + * @param {Circle} The Circle object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + **/ + function containsCircle(a, b) { + //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); + return true; + }; + CircleUtils.distanceBetween = /** + * Returns the distance from the center of the Circle object to the given object (can be Circle, Point or anything with x/y properties) + * @method distanceBetween + * @param {Circle} a - The Circle object. + * @param {Circle} b - The target object. Must have visible x and y properties that represent the center of the object. + * @param {Boolean} [optional] round - Round the distance to the nearest integer (default false) + * @return {Number} The distance between this Point object and the destination Point object. + **/ + function distanceBetween(a, target, round) { + if (typeof round === "undefined") { round = false; } + var dx = a.x - target.x; + var dy = a.y - target.y; + if(round === true) { + return Math.round(Math.sqrt(dx * dx + dy * dy)); + } else { + return Math.sqrt(dx * dx + dy * dy); + } + }; + CircleUtils.equals = /** + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + **/ + function equals(a, b) { + return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); + }; + CircleUtils.intersects = /** + * Determines whether the two Circle objects intersect. + * This method checks the radius distances between the two Circle objects to see if they intersect. + * @method intersects + * @param {Circle} a - The first Circle object. + * @param {Circle} b - The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + **/ + function intersects(a, b) { + return (CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); + }; + CircleUtils.circumferencePoint = /** + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Circle} a - The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + **/ + function circumferencePoint(a, angle, asDegrees, out) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof out === "undefined") { out = new Phaser.Point(); } + if(asDegrees === true) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + return out.setTo(a.x + a.radius * Math.cos(angle), a.y + a.radius * Math.sin(angle)); + }; + CircleUtils.intersectsRectangle = /* + public static boolean intersect(Rectangle r, Circle c) + { + float cx = Math.abs(c.x - r.x - r.halfWidth); + float xDist = r.halfWidth + c.radius; + if (cx > xDist) + return false; + float cy = Math.abs(c.y - r.y - r.halfHeight); + float yDist = r.halfHeight + c.radius; + if (cy > yDist) + return false; + if (cx <= r.halfWidth || cy <= r.halfHeight) + return true; + float xCornerDist = cx - r.halfWidth; + float yCornerDist = cy - r.halfHeight; + float xCornerDistSq = xCornerDist * xCornerDist; + float yCornerDistSq = yCornerDist * yCornerDist; + float maxCornerDistSq = c.radius * c.radius; + return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; + } + */ + function intersectsRectangle(c, r) { + var cx = Math.abs(c.x - r.x - r.halfWidth); + var xDist = r.halfWidth + c.radius; + if(cx > xDist) { + return false; + } + var cy = Math.abs(c.y - r.y - r.halfHeight); + var yDist = r.halfHeight + c.radius; + if(cy > yDist) { + return false; + } + if(cx <= r.halfWidth || cy <= r.halfHeight) { + return true; + } + var xCornerDist = cx - r.halfWidth; + var yCornerDist = cy - r.halfHeight; + var xCornerDistSq = xCornerDist * xCornerDist; + var yCornerDistSq = yCornerDist * yCornerDist; + var maxCornerDistSq = c.radius * c.radius; + return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; + }; + return CircleUtils; + })(); + Phaser.CircleUtils = CircleUtils; +})(Phaser || (Phaser = {})); +var Phaser; +(function (Phaser) { + /// + /// + /// + /// + /// + /** + * Phaser - PhysicsManager + * + * Your game only has one PhysicsManager instance and it's responsible for looking after, creating and colliding + * all of the physics objects in the world. + */ + (function (Physics) { + var PhysicsManager = (function () { + function PhysicsManager(game, width, height) { + this._length = 0; + /** + * @type {number} + */ + this.worldDivisions = 6; + this.game = game; + this.gravity = new Phaser.Vec2(); + this.drag = new Phaser.Vec2(); + this.bounce = new Phaser.Vec2(); + this.angularDrag = 0; + this.bounds = new Phaser.Rectangle(0, 0, width, height); + this._distance = new Phaser.Vec2(); + this._tangent = new Phaser.Vec2(); + this.members = new Phaser.Group(game); + } + PhysicsManager.OVERLAP_BIAS = 4; + PhysicsManager.TILE_OVERLAP = false; + PhysicsManager.prototype.updateMotion = /* + public update() { + + this._length = this._objects.length; + + for (var i = 0; i < this._length; i++) + { + if (this._objects[i]) + { + this._objects[i].preUpdate(); + this.updateMotion(this._objects[i]); + this.collideWorld(this._objects[i]); + + for (var x = 0; x < this._length; x++) + { + if (this._objects[x] && this._objects[x] !== this._objects[i]) + { + //this.collideShapes(this._objects[i], this._objects[x]); + var r = this.NEWseparate(this._objects[i], this._objects[x]); + //console.log('sep', r); + } + } + + } + } + + } + + public render() { + + // iterate through the objects here, updating and colliding + for (var i = 0; i < this._length; i++) + { + if (this._objects[i]) + { + this._objects[i].render(this.game.stage.context); + } + } + + } + */ + function (body) { + if(body.type == Phaser.Types.BODY_DISABLED) { + return; + } + this._velocityDelta = (this.computeVelocity(body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity) / 2; + body.angularVelocity += this._velocityDelta; + body.angle += body.angularVelocity * this.game.time.elapsed; + body.angularVelocity += this._velocityDelta; + this._velocityDelta = (this.computeVelocity(body.velocity.x, body.gravity.x, body.acceleration.x, body.drag.x) - body.velocity.x) / 2; + body.velocity.x += this._velocityDelta; + this._delta = body.velocity.x * this.game.time.elapsed; + body.velocity.x += this._velocityDelta; + body.position.x += this._delta; + this._velocityDelta = (this.computeVelocity(body.velocity.y, body.gravity.y, body.acceleration.y, body.drag.y) - body.velocity.y) / 2; + body.velocity.y += this._velocityDelta; + this._delta = body.velocity.y * this.game.time.elapsed; + body.velocity.y += this._velocityDelta; + body.position.y += this._delta; + }; + PhysicsManager.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. + */ + function (velocity, gravity, acceleration, drag, max) { + if (typeof gravity === "undefined") { gravity = 0; } + if (typeof acceleration === "undefined") { acceleration = 0; } + if (typeof drag === "undefined") { drag = 0; } + if (typeof max === "undefined") { max = 10000; } + if(acceleration !== 0) { + velocity += (acceleration + gravity) * this.game.time.elapsed; + } else if(drag !== 0) { + this._drag = drag * this.game.time.elapsed; + if(velocity - this._drag > 0) { + velocity = velocity - this._drag; + } else if(velocity + this._drag < 0) { + velocity += this._drag; + } else { + velocity = 0; + } + velocity += gravity; + } + if((velocity != 0) && (max != 10000)) { + if(velocity > max) { + velocity = max; + } else if(velocity < -max) { + velocity = -max; + } + } + return velocity; + }; + PhysicsManager.prototype.separate = /** + * The core Collision separation method. + * @param body1 The first Physics.Body to separate + * @param body2 The second Physics.Body to separate + * @returns {boolean} Returns true if the bodies were separated, otherwise false. + */ + function (body1, body2) { + this._separatedX = this.separateBodyX(body1, body2); + this._separatedY = this.separateBodyY(body1, body2); + return this._separatedX || this._separatedY; + }; + PhysicsManager.prototype.checkHullIntersection = function (body1, body2) { + return ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)); + //if ((body1.hullX + body1.hullWidth > body2.hullX) && (body1.hullX < body2.hullX + body2.hullWidth) && (body1.hullY + body1.hullHeight > body2.hullY) && (body1.hullY < body2.hullY + body2.hullHeight)) + //{ + // return true; + //} + //else + //{ + // return false; + //} + }; + PhysicsManager.prototype.separateBodyX = /** + * 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 (body1, body2) { + // Can't separate two disabled or static objects + if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { + return false; + } + // First, get the two object deltas + this._overlap = 0; + if(body1.deltaX != body2.deltaX) { + if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { + this._maxOverlap = body1.deltaXAbs + body2.deltaXAbs + PhysicsManager.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(body1.deltaX > body2.deltaX) { + this._overlap = body1.bounds.right - body2.bounds.x; + if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.RIGHT) || !(body2.allowCollisions & Phaser.Types.LEFT)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.RIGHT; + body2.touching |= Phaser.Types.LEFT; + } + } else if(body1.deltaX < body2.deltaX) { + this._overlap = body1.bounds.x - body2.bounds.width - body2.bounds.x; + if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.LEFT) || !(body2.allowCollisions & Phaser.Types.RIGHT)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.LEFT; + body2.touching |= Phaser.Types.RIGHT; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(this._overlap != 0) { + this._obj1Velocity = body1.velocity.x; + this._obj2Velocity = body2.velocity.x; + /** + * Dynamic = gives and receives impacts + * Static = gives but doesn't receive impacts, cannot be moved by physics + * Kinematic = gives impacts, but never receives, can be moved by physics + */ + // 2 dynamic bodies will exchange velocities + if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 0.5; + body1.position.x = body1.position.x - this._overlap; + body2.position.x += this._overlap; + this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); + this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); + this._average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; + this._obj1NewVelocity -= this._average; + this._obj2NewVelocity -= this._average; + body1.velocity.x = this._average + this._obj1NewVelocity * body1.bounce.x; + body2.velocity.x = this._average + this._obj2NewVelocity * body2.bounce.x; + } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { + // Body 2 is Static or Kinematic + this._overlap *= 2; + body1.position.x -= this._overlap; + body1.velocity.x = this._obj2Velocity - this._obj1Velocity * body1.bounce.x; + } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { + // Body 1 is Static or Kinematic + this._overlap *= 2; + body2.position.x += this._overlap; + body2.velocity.x = this._obj1Velocity - this._obj2Velocity * body2.bounce.x; + } + return true; + } else { + return false; + } + }; + PhysicsManager.prototype.separateBodyY = /** + * 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 (body1, body2) { + // Can't separate two immovable objects + if((body1.type == Phaser.Types.BODY_DISABLED || body1.type == Phaser.Types.BODY_STATIC) && (body2.type == Phaser.Types.BODY_DISABLED || body2.type == Phaser.Types.BODY_STATIC)) { + return false; + } + // First, get the two object deltas + this._overlap = 0; + if(body1.deltaY != body2.deltaY) { + if(Phaser.RectangleUtils.intersects(body1.bounds, body2.bounds)) { + // This is the only place to use the DeltaAbs values + this._maxOverlap = body1.deltaYAbs + body2.deltaYAbs + PhysicsManager.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(body1.deltaY > body2.deltaY) { + this._overlap = body1.bounds.bottom - body2.bounds.y; + if((this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.DOWN) || !(body2.allowCollisions & Phaser.Types.UP)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.DOWN; + body2.touching |= Phaser.Types.UP; + } + } else if(body1.deltaY < body2.deltaY) { + this._overlap = body1.bounds.y - body2.bounds.height - body2.bounds.y; + if((-this._overlap > this._maxOverlap) || !(body1.allowCollisions & Phaser.Types.UP) || !(body2.allowCollisions & Phaser.Types.DOWN)) { + this._overlap = 0; + } else { + body1.touching |= Phaser.Types.UP; + body2.touching |= Phaser.Types.DOWN; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(this._overlap != 0) { + this._obj1Velocity = body1.velocity.y; + this._obj2Velocity = body2.velocity.y; + /** + * Dynamic = gives and receives impacts + * Static = gives but doesn't receive impacts, cannot be moved by physics + * Kinematic = gives impacts, but never receives, can be moved by physics + */ + if(body1.type == Phaser.Types.BODY_DYNAMIC && body2.type == Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 0.5; + body1.position.y = body1.position.y - this._overlap; + body2.position.y += this._overlap; + this._obj1NewVelocity = Math.sqrt((this._obj2Velocity * this._obj2Velocity * body2.mass) / body1.mass) * ((this._obj2Velocity > 0) ? 1 : -1); + this._obj2NewVelocity = Math.sqrt((this._obj1Velocity * this._obj1Velocity * body1.mass) / body2.mass) * ((this._obj1Velocity > 0) ? 1 : -1); + var average = (this._obj1NewVelocity + this._obj2NewVelocity) * 0.5; + this._obj1NewVelocity -= average; + this._obj2NewVelocity -= average; + body1.velocity.y = average + this._obj1NewVelocity * body1.bounce.y; + body2.velocity.y = average + this._obj2NewVelocity * body2.bounce.y; + } else if(body2.type != Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 2; + body1.position.y -= this._overlap; + body1.velocity.y = this._obj2Velocity - this._obj1Velocity * body1.bounce.y; + // This is special case code that handles things like horizontal moving platforms you can ride + //if (body2.parent.active && body2.moves && (body1.deltaY > body2.deltaY)) + if(body2.parent.active && (body1.deltaY > body2.deltaY)) { + body1.position.x += body2.position.x - body2.oldPosition.x; + } + } else if(body1.type != Phaser.Types.BODY_DYNAMIC) { + this._overlap *= 2; + body2.position.y += this._overlap; + body2.velocity.y = this._obj1Velocity - this._obj2Velocity * body2.bounce.y; + // This is special case code that handles things like horizontal moving platforms you can ride + //if (object1.active && body1.moves && (body1.deltaY < body2.deltaY)) + if(body1.parent.active && (body1.deltaY < body2.deltaY)) { + body2.position.x += body1.position.x - body1.oldPosition.x; + } + } + return true; + } else { + return false; + } + }; + PhysicsManager.prototype.overlap = /* + private TILEseparate(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('1 The left side of ShapeA hit the right side of ShapeB', Math.floor(distance.x)); + shapeA.physics.touching |= Phaser.Types.LEFT; + shapeB.physics.touching |= Phaser.Types.RIGHT; + } + else if (tangent.x == -1) + { + console.log('2 The right side of ShapeA hit the left side of ShapeB', Math.floor(distance.x)); + shapeA.physics.touching |= Phaser.Types.RIGHT; + shapeB.physics.touching |= Phaser.Types.LEFT; + } + + if (tangent.y == 1) + { + console.log('3 The top of ShapeA hit the bottom of ShapeB', Math.floor(distance.y)); + shapeA.physics.touching |= Phaser.Types.UP; + shapeB.physics.touching |= Phaser.Types.DOWN; + } + else if (tangent.y == -1) + { + console.log('4 The bottom of ShapeA hit the top of ShapeB', Math.floor(distance.y)); + shapeA.physics.touching |= Phaser.Types.DOWN; + shapeB.physics.touching |= Phaser.Types.UP; + } + + + // only apply collision response forces if the object is travelling into, and not out of, the collision + var dot = Vec2Utils.dot(shapeA.physics.velocity, tangent); + + if (dot < 0) + { + console.log('in to', dot); + + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + else + { + console.log('out of', dot); + } + + shapeA.position.x += Math.floor(distance.x); + //shapeA.bounds.x += Math.floor(distance.x); + + shapeA.position.y += Math.floor(distance.y); + //shapeA.bounds.y += distance.y; + + console.log('------------------------------------------------'); + + } + + private collideWorld(shape:IPhysicsShape) { + + // Collide on the x-axis + this._distance.x = shape.world.bounds.x - (shape.position.x - shape.bounds.halfWidth); + + if (0 < this._distance.x) + { + // Hit Left + this._tangent.setTo(1, 0); + this.separateXWall(shape, this._distance, this._tangent); + } + else + { + this._distance.x = (shape.position.x + shape.bounds.halfWidth) - shape.world.bounds.right; + + if (0 < this._distance.x) + { + // Hit Right + this._tangent.setTo(-1, 0); + this._distance.reverse(); + this.separateXWall(shape, this._distance, this._tangent); + } + } + + // Collide on the y-axis + this._distance.y = shape.world.bounds.y - (shape.position.y - shape.bounds.halfHeight); + + if (0 < this._distance.y) + { + // Hit Top + this._tangent.setTo(0, 1); + this.separateYWall(shape, this._distance, this._tangent); + } + else + { + this._distance.y = (shape.position.y + shape.bounds.halfHeight) - shape.world.bounds.bottom; + + if (0 < this._distance.y) + { + // Hit Bottom + this._tangent.setTo(0, -1); + this._distance.reverse(); + this.separateYWall(shape, this._distance, this._tangent); + } + } + + } + + private separateX(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.LEFT; + shapeB.physics.touching |= Phaser.Types.RIGHT; + } + else + { + console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.RIGHT; + shapeB.physics.touching |= Phaser.Types.LEFT; + } + + // collision edges + //shapeA.oH = tangent.x; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + } + + shapeA.position.x += distance.x; + shapeA.bounds.x += distance.x; + + } + + private separateY(shapeA: IPhysicsShape, shapeB: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.y == 1) + { + console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.UP; + shapeB.physics.touching |= Phaser.Types.DOWN; + } + else + { + console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.DOWN; + shapeB.physics.touching |= Phaser.Types.UP; + } + + // collision edges + //shapeA.oV = tangent.y; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + + shapeA.position.y += distance.y; + shapeA.bounds.y += distance.y; + + } + + private separateXWall(shapeA: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.x == 1) + { + console.log('The left side of ShapeA hit the right side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.LEFT; + } + else + { + console.log('The right side of ShapeA hit the left side of ShapeB', distance.x); + shapeA.physics.touching |= Phaser.Types.RIGHT; + } + + // collision edges + //shapeA.oH = tangent.x; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.x > 0) + { + shapeA.physics.velocity.x *= -(shapeA.physics.bounce.x); + } + else + { + shapeA.physics.velocity.x = 0; + } + } + + shapeA.position.x += distance.x; + + } + + private separateYWall(shapeA: IPhysicsShape, distance: Vec2, tangent: Vec2) { + + if (tangent.y == 1) + { + console.log('The top of ShapeA hit the bottom of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.UP; + } + else + { + console.log('The bottom of ShapeA hit the top of ShapeB', distance.y); + shapeA.physics.touching |= Phaser.Types.DOWN; + } + + // collision edges + //shapeA.oV = tangent.y; + + // only apply collision response forces if the object is travelling into, and not out of, the collision + if (Vec2Utils.dot(shapeA.physics.velocity, tangent) < 0) + { + // Apply horizontal bounce + if (shapeA.physics.bounce.y > 0) + { + shapeA.physics.velocity.y *= -(shapeA.physics.bounce.y); + } + else + { + shapeA.physics.velocity.y = 0; + } + } + + shapeA.position.y += distance.y; + + } + */ + /** + * Checks for overlaps between two objects using the world QuadTree. Can be Sprite vs. Sprite, Sprite 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 Sprite or Group to check. If null the world.group is used. + * @param object2 The second Sprite 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.worldDivisions; + this._quadTree = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.width, this.bounds.height); + this._quadTree.load(object1, object2, notifyCallback, processCallback, context); + this._quadTreeResult = this._quadTree.execute(); + this._quadTree.destroy(); + this._quadTree = null; + return this._quadTreeResult; + }; + PhysicsManager.prototype.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 (object, x, y, width, height, mass, collideLeft, collideRight, collideUp, collideDown, separateX, separateY) { + //var separatedX: bool = this.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); + //var separatedY: bool = this.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); + //return separatedX || separatedY; + return false; + }; + return PhysicsManager; + })(); + Physics.PhysicsManager = PhysicsManager; + /** + * 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. + */ + /* + public separateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + var objDelta: number = object.x - object.last.x; + //var objDelta: number = object.collisionMask.deltaX; + + if (objDelta != 0) + { + // Check if the X hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //var objDeltaAbs: number = object.collisionMask.deltaXAbs; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.x + object.width - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (objDelta < 0) + { + overlap = object.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + //console.log(' + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + /** + * 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. + */ + /* + public separateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 0; + var objDelta: number = object.y - object.last.y; + + if (objDelta != 0) + { + // Check if the Y hulls actually overlap + var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + 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)) + { + var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (objDelta > 0) + { + overlap = object.y + object.height - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (objDelta < 0) + { + overlap = object.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + /** + * 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. + */ + /* + public static NEWseparateTileX(object:Sprite, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the object delta + var overlap: number = 0; + + if (object.collisionMask.deltaX != 0) + { + // Check if the X hulls actually overlap + //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //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)) + { + var maxOverlap: number = object.collisionMask.deltaXAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaX > 0) + { + //overlap = object.x + object.width - x; + overlap = object.collisionMask.right - x; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.RIGHT) || collideLeft == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.RIGHT; + } + } + else if (object.collisionMask.deltaX < 0) + { + //overlap = object.x - width - x; + overlap = object.collisionMask.x - width - x; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.LEFT) || collideRight == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.LEFT; + } + + } + + } + } + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + + } + */ + /** + * 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. + */ + /* + public NEWseparateTileY(object: Sprite, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool, separate: bool): bool { + + // Can't separate two immovable objects (tiles are always immovable) + if (object.immovable) + { + return false; + } + + // First, get the two object deltas + var overlap: number = 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: 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)) + { + //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + var maxOverlap: number = object.collisionMask.deltaYAbs + Collision.OVERLAP_BIAS; + + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if (object.collisionMask.deltaY > 0) + { + //overlap = object.y + object.height - y; + overlap = object.collisionMask.bottom - y; + + if ((overlap > maxOverlap) || !(object.allowCollisions & Collision.DOWN) || collideUp == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.DOWN; + } + } + else if (object.collisionMask.deltaY < 0) + { + //overlap = object.y - height - y; + overlap = object.collisionMask.y - height - y; + + if ((-overlap > maxOverlap) || !(object.allowCollisions & Collision.UP) || collideDown == false) + { + overlap = 0; + } + else + { + object.touching |= Collision.UP; + } + } + } + } + + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + + // Then adjust their positions and velocities accordingly (if there was any overlap) + if (overlap != 0) + { + if (separate == true) + { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + + Collision.TILE_OVERLAP = true; + return true; + } + else + { + return false; + } + } + */ + })(Phaser.Physics || (Phaser.Physics = {})); + var Physics = Phaser.Physics; +})(Phaser || (Phaser = {})); /// /// /// @@ -9461,13 +11540,12 @@ var Phaser; this.group = new Phaser.Group(this._game, 0); this.bounds = new Phaser.Rectangle(0, 0, width, height); this.physics = new Phaser.Physics.PhysicsManager(this._game, width, height); - this.worldDivisions = 6; } World.prototype.update = /** * This is called automatically every frame, and is where main logic happens. */ function () { - this.physics.update(); + //this.physics.update(); this.group.update(); this.cameras.update(); }; @@ -9559,6 +11637,282 @@ var Phaser; })(); Phaser.World = World; })(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.game = game; + } + Motion.prototype.velocityFromAngle = /** + * Given the angle and speed calculate the velocity and return it as a Point + * + * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + function (angle, speed) { + if(isNaN(speed)) { + speed = 0; + } + var a = this.game.math.degreesToRadians(angle); + return new Phaser.Point((Math.cos(a) * speed), (Math.sin(a) * speed)); + }; + Motion.prototype.moveTowardsObject = /** + * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * If you need the object to accelerate, see accelerateTowardsObject() instead + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) + * + * @param {Sprite} source The Sprite on which the velocity will be set + * @param {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsObject = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsObject() instead. + * + * @param {Sprite} source The Sprite on which the acceleration will be set + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.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 {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsMouse = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsMouse() instead. + * + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.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 {Sprite} 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.body.velocity.x = Math.cos(a) * speed; + source.body.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsPoint = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsPoint() instead. + * + * @param {Sprite} 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.body.velocity.x = 0; + source.body.velocity.y = 0; + source.body.acceleration.x = Math.cos(a) * speed; + source.body.acceleration.y = Math.sin(a) * speed; + source.body.maxVelocity.x = xSpeedMax; + source.body.maxVelocity.y = ySpeedMax; + }; + Motion.prototype.distanceBetween = /** + * Find the distance between two Sprites, taking their origin into account + * + * @param {Sprite} a The first Sprite + * @param {Sprite} b The second Sprite + * @return {number} int Distance (in pixels) + */ + function (a, b) { + return Phaser.Vec2Utils.distance(a.body.position, b.body.position); + }; + Motion.prototype.distanceToPoint = /** + * Find the distance from an Sprite to the given Point, taking the source origin into account + * + * @param {Sprite} 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 {Sprite} 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 {Sprite} a The Sprite to test from + * @param {Point} target The Point to angle the Sprite towards + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + function (a, target, asDegrees) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + var dx = (target.x) - (a.x + a.origin.x); + var dy = (target.y) - (a.y + a.origin.y); + if(asDegrees) { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + 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 {Sprite} a The Sprite to test from + * @param {Sprite} 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(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + Motion.prototype.velocityFromFacing = /** + * Given the Sprite and speed calculate the velocity and return it as an Point based on the direction the sprite is facing + * + * @param {Sprite} 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.body.facing == Phaser.Types.LEFT) { + a = this.game.math.degreesToRadians(180); + } else if(parent.body.facing == Phaser.Types.RIGHT) { + a = this.game.math.degreesToRadians(0); + } else if(parent.body.facing == Phaser.Types.UP) { + a = this.game.math.degreesToRadians(-90); + } else if(parent.body.facing == Phaser.Types.DOWN) { + a = this.game.math.degreesToRadians(90); + } + return new Phaser.Point(Math.cos(a) * speed, 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 {Sprite} 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 = Phaser.SpriteUtils.getScreenXY(a); + var dx = a.game.input.x - p.x; + var dy = a.game.input.y - p.y; + if(asDegrees) { + return this.game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + return Motion; + })(); + Phaser.Motion = Motion; +})(Phaser || (Phaser = {})); /// /** * Phaser - Device @@ -11921,271 +14275,6 @@ var Phaser; Phaser.HeadlessRenderer = HeadlessRenderer; })(Phaser || (Phaser = {})); /// -/// -/// -/** -* Phaser - ScrollRegion -* -* Creates a scrolling region within a ScrollZone. -* It is scrolled via the scrollSpeed.x/y properties. -*/ -var Phaser; -(function (Phaser) { - var ScrollRegion = (function () { - /** - * ScrollRegion constructor - * Create a new ScrollRegion. - * - * @param x {number} X position in world coordinate. - * @param y {number} Y position in world coordinate. - * @param width {number} Width of this object. - * @param height {number} Height of this object. - * @param speedX {number} X-axis scrolling speed. - * @param speedY {number} Y-axis scrolling speed. - */ - function ScrollRegion(x, y, width, height, speedX, speedY) { - this._anchorWidth = 0; - this._anchorHeight = 0; - this._inverseWidth = 0; - this._inverseHeight = 0; - /** - * Will this region be rendered? (default to true) - * @type {boolean} - */ - this.visible = true; - // Our seamless scrolling quads - this._A = new Phaser.Rectangle(x, y, width, height); - this._B = new Phaser.Rectangle(x, y, width, height); - this._C = new Phaser.Rectangle(x, y, width, height); - this._D = new Phaser.Rectangle(x, y, width, height); - this._scroll = new Phaser.Vec2(); - this._bounds = new Phaser.Rectangle(x, y, width, height); - this.scrollSpeed = new Phaser.Vec2(speedX, speedY); - } - ScrollRegion.prototype.update = /** - * Update region scrolling with tick time. - * @param delta {number} Elapsed time since last update. - */ - function (delta) { - this._scroll.x += this.scrollSpeed.x; - this._scroll.y += this.scrollSpeed.y; - if(this._scroll.x > this._bounds.right) { - this._scroll.x = this._bounds.x; - } - if(this._scroll.x < this._bounds.x) { - this._scroll.x = this._bounds.right; - } - if(this._scroll.y > this._bounds.bottom) { - this._scroll.y = this._bounds.y; - } - if(this._scroll.y < this._bounds.y) { - this._scroll.y = this._bounds.bottom; - } - // Anchor Dimensions - this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x; - this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y; - if(this._anchorWidth > this._bounds.width) { - this._anchorWidth = this._bounds.width; - } - if(this._anchorHeight > this._bounds.height) { - this._anchorHeight = this._bounds.height; - } - this._inverseWidth = this._bounds.width - this._anchorWidth; - this._inverseHeight = this._bounds.height - this._anchorHeight; - // Rectangle A - this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight); - // Rectangle B - this._B.y = this._scroll.y; - this._B.width = this._inverseWidth; - this._B.height = this._anchorHeight; - // Rectangle C - this._C.x = this._scroll.x; - this._C.width = this._anchorWidth; - this._C.height = this._inverseHeight; - // Rectangle D - this._D.width = this._inverseWidth; - this._D.height = this._inverseHeight; - }; - ScrollRegion.prototype.render = /** - * Render this region to specific context. - * @param context {CanvasRenderingContext2D} Canvas context this region will be rendered to. - * @param texture {object} The texture to be rendered. - * @param dx {number} X position in world coordinate. - * @param dy {number} Y position in world coordinate. - * @param width {number} Width of this region to be rendered. - * @param height {number} Height of this region to be rendered. - */ - function (context, texture, dx, dy, dw, dh) { - if(this.visible == false) { - return; - } - // dx/dy are the world coordinates to render the FULL ScrollZone into. - // This ScrollRegion may be smaller than that and offset from the dx/dy coordinates. - this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0); - this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0); - this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height); - this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height); - //context.fillStyle = 'rgb(255,255,255)'; - //context.font = '18px Arial'; - //context.fillText('RectangleA: ' + this._A.toString(), 32, 450); - //context.fillText('RectangleB: ' + this._B.toString(), 32, 480); - //context.fillText('RectangleC: ' + this._C.toString(), 32, 510); - //context.fillText('RectangleD: ' + this._D.toString(), 32, 540); - }; - ScrollRegion.prototype.crop = /** - * Crop part of the texture and render it to the given context. - * @param context {CanvasRenderingContext2D} Canvas context the texture will be rendered to. - * @param texture {object} Texture to be rendered. - * @param srcX {number} Target region top-left x coordinate in the texture. - * @param srcX {number} Target region top-left y coordinate in the texture. - * @param srcW {number} Target region width in the texture. - * @param srcH {number} Target region height in the texture. - * @param destX {number} Render region top-left x coordinate in the context. - * @param destX {number} Render region top-left y coordinate in the context. - * @param destW {number} Target region width in the context. - * @param destH {number} Target region height in the context. - * @param offsetX {number} X offset to the context. - * @param offsetY {number} Y offset to the context. - */ - function (context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) { - offsetX += destX; - offsetY += destY; - if(srcW > (destX + destW) - offsetX) { - srcW = (destX + destW) - offsetX; - } - if(srcH > (destY + destH) - offsetY) { - srcH = (destY + destH) - offsetY; - } - srcX = Math.floor(srcX); - srcY = Math.floor(srcY); - srcW = Math.floor(srcW); - srcH = Math.floor(srcH); - offsetX = Math.floor(offsetX + this._bounds.x); - offsetY = Math.floor(offsetY + this._bounds.y); - if(srcW > 0 && srcH > 0) { - context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH); - } - }; - return ScrollRegion; - })(); - Phaser.ScrollRegion = ScrollRegion; -})(Phaser || (Phaser = {})); -var __extends = this.__extends || function (d, b) { - function __() { this.constructor = d; } - __.prototype = b.prototype; - d.prototype = new __(); -}; -/// -/// -/// -/** -* 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, key, width, height); - this.type = Phaser.Types.SCROLLZONE; - this.render = game.renderer.renderScrollZone; - this.physics.moves = false; - this.regions = []; - if(this.texture.loaded) { - if(width > this.width || height > this.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.width || height < this.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.createRepeatingTexture = /** - * Create repeating texture with _texture, and store it into the _dynamicTexture. - * Used to create texture when texture image is small than size of the zone. - */ - function (regionWidth, regionHeight) { - // Work out how many we'll need of the source image to make it tile properly - var tileWidth = Math.ceil(this.width / regionWidth) * regionWidth; - var tileHeight = Math.ceil(this.height / regionHeight) * regionHeight; - var dt = new Phaser.DynamicTexture(this.game, tileWidth, tileHeight); - dt.context.rect(0, 0, tileWidth, tileHeight); - dt.context.fillStyle = dt.context.createPattern(this.texture.imageTexture, "repeat"); - dt.context.fill(); - this.texture.loadDynamicTexture(dt); - }; - return ScrollZone; - })(Phaser.Sprite); - Phaser.ScrollZone = ScrollZone; -})(Phaser || (Phaser = {})); -/// /// /// /// @@ -12220,8 +14309,6 @@ var Phaser; this._game.world.group.render(this, this._camera); this._camera.postRender(); } - // Physics Debug layer - this._game.world.physics.render(); }; CanvasRenderer.prototype.renderSprite = /** * Render this sprite to specific camera. Called by game loop after update(). @@ -12270,9 +14357,9 @@ var Phaser; } // Rotation and Flipped if(sprite.modified) { - if(sprite.texture.renderRotation == true && (sprite.rotation !== 0 || sprite.rotationOffset !== 0)) { - this._sin = Math.sin(sprite.game.math.degreesToRadians(sprite.rotationOffset + sprite.rotation)); - this._cos = Math.cos(sprite.game.math.degreesToRadians(sprite.rotationOffset + sprite.rotation)); + if(sprite.texture.renderRotation == true && (sprite.angle !== 0 || sprite.angleOffset !== 0)) { + this._sin = Math.sin(sprite.game.math.degreesToRadians(sprite.angleOffset + sprite.angle)); + this._cos = Math.cos(sprite.game.math.degreesToRadians(sprite.angleOffset + sprite.angle)); } // setTransform(a, b, c, d, e, f); // a = scale x @@ -12318,11 +14405,6 @@ var Phaser; if(sprite.modified) { sprite.texture.context.restore(); } - //if (this.renderDebug) - //{ - // this.renderBounds(camera, cameraOffsetX, cameraOffsetY); - //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); - //} if(this._ga > -1) { sprite.texture.context.globalAlpha = this._ga; } @@ -12362,9 +14444,9 @@ var Phaser; } // Rotation and Flipped if(scrollZone.modified) { - if(scrollZone.texture.renderRotation == true && (scrollZone.rotation !== 0 || scrollZone.rotationOffset !== 0)) { - this._sin = Math.sin(scrollZone.game.math.degreesToRadians(scrollZone.rotationOffset + scrollZone.rotation)); - this._cos = Math.cos(scrollZone.game.math.degreesToRadians(scrollZone.rotationOffset + scrollZone.rotation)); + if(scrollZone.texture.renderRotation == true && (scrollZone.angle !== 0 || scrollZone.angleOffset !== 0)) { + this._sin = Math.sin(scrollZone.game.math.degreesToRadians(scrollZone.angleOffset + scrollZone.angle)); + this._cos = Math.cos(scrollZone.game.math.degreesToRadians(scrollZone.angleOffset + scrollZone.angle)); } // setTransform(a, b, c, d, e, f); // a = scale x @@ -12401,11 +14483,6 @@ var Phaser; if(scrollZone.modified) { scrollZone.texture.context.restore(); } - //if (this.renderDebug) - //{ - // this.renderBounds(camera, cameraOffsetX, cameraOffsetY); - //this.collisionMask.render(camera, cameraOffsetX, cameraOffsetY); - //} if(this._ga > -1) { scrollZone.texture.context.globalAlpha = this._ga; } @@ -12415,20 +14492,27 @@ var Phaser; })(); Phaser.CanvasRenderer = CanvasRenderer; })(Phaser || (Phaser = {})); +/// +/// +/// +/// +/// +/// +/// +/// +/// /// /// /// /// /// /// -/// -/// -/// /// /// /// /// /// +/// /// /// /// @@ -12583,14 +14667,13 @@ var Phaser; }, 13); } else { this.device = new Phaser.Device(); - //this.motion = new Motion(this); + 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 Collision(this); this.loader = new Phaser.Loader(this, this.loadComplete); this.time = new Phaser.Time(this); this.tweens = new Phaser.TweenManager(this); @@ -12837,21 +14920,25 @@ var Phaser; enumerable: true, configurable: true }); + Game.prototype.collide = /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, context) { + if (typeof objectOrGroup1 === "undefined") { objectOrGroup1 = null; } + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof context === "undefined") { context = this.callbackContext; } + return this.world.physics.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, this.world.physics.separate, context); + }; 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 () { + get: function () { return this.world.cameras.current; }, enumerable: true, @@ -12861,288 +14948,115 @@ var Phaser; })(); Phaser.Game = Game; })(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); + /// + /// + /// + /** + * Phaser - Components - Events + * + * + */ + (function (Components) { + var Events = (function () { + function Events(parent, key) { + if (typeof key === "undefined") { key = ''; } + this._game = parent.game; + this._sprite = parent; } - }; - 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.multiplyByScalar = /** - * Multiply 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.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.equals = /** - * Check if both the x and y of this vector equal the given value. - * - * @return {Boolean} - */ - function (value) { - return (this.x == value && this.y == value); - }; - 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; + return Events; + })(); + Components.Events = Events; + })(Phaser.Components || (Phaser.Components = {})); + var Components = Phaser.Components; })(Phaser || (Phaser = {})); var Phaser; (function (Phaser) { - /// - /// - /// - /// - /// - /// - /// /** - * Phaser - Components - Physics + * Phaser - Components - Debug + * + * */ (function (Components) { - var Physics = (function () { - function Physics(parent) { + var Debug = (function () { + function Debug() { /** - * Whether this object will be moved by impacts with other objects or not. + * Render bound of this sprite for debugging? (default to false) * @type {boolean} */ - this.immovable = false; + this.renderDebug = false; /** - * Set this to false if you want to skip the automatic movement stuff - * @type {boolean} + * Color of the Sprite when no image is present. Format is a css color string. + * @type {string} */ - this.moves = true; - this.mass = 1; - this.game = parent.game; - this._sprite = parent; - this.gravity = Phaser.Vec2Utils.clone(this.game.world.physics.gravity); - this.drag = Phaser.Vec2Utils.clone(this.game.world.physics.drag); - this.bounce = Phaser.Vec2Utils.clone(this.game.world.physics.bounce); - this.friction = Phaser.Vec2Utils.clone(this.game.world.physics.friction); - this.velocity = new Phaser.Vec2(); - this.acceleration = new Phaser.Vec2(); - this.touching = Phaser.Types.NONE; - this.wasTouching = Phaser.Types.NONE; - this.allowCollisions = Phaser.Types.ANY; - this.shape = this.game.world.physics.add(new Phaser.Physics.AABB(this.game, this._sprite, this._sprite.x, this._sprite.y, this._sprite.width, this._sprite.height)); + 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)'; } - Physics.prototype.setCircle = function (diameter) { - // Here is the stuff I want to remove - this.game.world.physics.remove(this.shape); - this.shape = this.game.world.physics.add(new Phaser.Physics.Circle(this.game, this._sprite, this._sprite.x, this._sprite.y, diameter)); - this._sprite.physics.shape.physics = this; - }; - Physics.prototype.update = /** - * Internal function for updating the position and speed of this object. - */ - function () { - // if this is all it does maybe move elsewhere? Sprite postUpdate? - if(this.moves && this.shape) { - this._sprite.x = (this.shape.position.x - this.shape.bounds.halfWidth) - this.shape.offset.x; - this._sprite.y = (this.shape.position.y - this.shape.bounds.halfHeight) - this.shape.offset.y; - } - }; - Physics.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._sprite.texture.context.fillStyle = color; - this._sprite.texture.context.fillText('Sprite: (' + this._sprite.frameBounds.width + ' x ' + this._sprite.frameBounds.height + ')', x, y); - //this._sprite.texture.context.fillText('x: ' + this._sprite.frameBounds.x.toFixed(1) + ' y: ' + this._sprite.frameBounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('x: ' + this.shape.bounds.x.toFixed(1) + ' y: ' + this.shape.bounds.y.toFixed(1) + ' rotation: ' + this._sprite.rotation.toFixed(1), x, y + 14); - this._sprite.texture.context.fillText('vx: ' + this.velocity.x.toFixed(1) + ' vy: ' + this.velocity.y.toFixed(1), x, y + 28); - this._sprite.texture.context.fillText('ax: ' + this.acceleration.x.toFixed(1) + ' ay: ' + this.acceleration.y.toFixed(1), x, y + 42); - }; - return Physics; + return Debug; })(); - Components.Physics = Physics; - })(Phaser.Components || (Phaser.Components = {})); + Components.Debug = Debug; + /** + * 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); + + } + */ + })(Phaser.Components || (Phaser.Components = {})); var Components = Phaser.Components; })(Phaser || (Phaser = {})); /// @@ -13180,407 +15094,6 @@ var Phaser; })(); Phaser.Polygon = Polygon; })(Phaser || (Phaser = {})); -var Phaser; -(function (Phaser) { - /// - /// - /// - /// - /// - /// - /** - * Phaser - Physics - Fixture - */ - (function (Physics) { - var Fixture = (function () { - function Fixture(parent, type) { - this.parent = parent; - // these are shape properties really - this.bounce = Phaser.Vec2Utils.clone(this.game.world.physics.bounce); - this.friction = Phaser.Vec2Utils.clone(this.game.world.physics.friction); - } - return Fixture; - })(); - Physics.Fixture = Fixture; - })(Phaser.Physics || (Phaser.Physics = {})); - var Physics = Phaser.Physics; -})(Phaser || (Phaser = {})); -/// -/// -/// -/** -* Phaser - QuadTree -* -* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. -* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, -* or the A list against the B list. Handy for different things! -*/ -var Phaser; -(function (Phaser) { - var QuadTree = (function (_super) { - __extends(QuadTree, _super); - /** - * Instantiate a new Quad Tree node. - * - * @param {Number} x The X-coordinate of the point in space. - * @param {Number} y The Y-coordinate of the point in space. - * @param {Number} width Desired width of this node. - * @param {Number} height Desired height of this node. - * @param {Number} parent The parent branch or node. Pass null to create a root. - */ - function QuadTree(x, y, width, height, parent) { - if (typeof parent === "undefined") { parent = null; } - _super.call(this, x, y, width, height); - this._headA = this._tailA = new Phaser.LinkedList(); - this._headB = this._tailB = new Phaser.LinkedList(); - //Copy the parent's children (if there are any) - if(parent != null) { - if(parent._headA.object != null) { - this._iterator = parent._headA; - while(this._iterator != null) { - if(this._tailA.object != null) { - this._ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - this._ot.next = this._tailA; - } - this._tailA.object = this._iterator.object; - this._iterator = this._iterator.next; - } - } - if(parent._headB.object != null) { - this._iterator = parent._headB; - while(this._iterator != null) { - if(this._tailB.object != null) { - this._ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - this._ot.next = this._tailB; - } - this._tailB.object = this._iterator.object; - this._iterator = this._iterator.next; - } - } - } else { - QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); - } - this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); - //Set up comparison/sort helpers - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - this._leftEdge = this.x; - this._rightEdge = this.x + this.width; - this._halfWidth = this.width / 2; - this._midpointX = this._leftEdge + this._halfWidth; - this._topEdge = this.y; - this._bottomEdge = this.y + this.height; - this._halfHeight = this.height / 2; - this._midpointY = this._topEdge + this._halfHeight; - } - QuadTree.A_LIST = 0; - QuadTree.B_LIST = 1; - QuadTree.prototype.destroy = /** - * Clean up memory. - */ - function () { - this._tailA.destroy(); - this._tailB.destroy(); - this._headA.destroy(); - this._headB.destroy(); - this._tailA = null; - this._tailB = null; - this._headA = null; - this._headB = null; - if(this._northWestTree != null) { - this._northWestTree.destroy(); - } - if(this._northEastTree != null) { - this._northEastTree.destroy(); - } - if(this._southEastTree != null) { - this._southEastTree.destroy(); - } - if(this._southWestTree != null) { - this._southWestTree.destroy(); - } - this._northWestTree = null; - this._northEastTree = null; - this._southEastTree = null; - this._southWestTree = null; - QuadTree._object = null; - QuadTree._processingCallback = null; - QuadTree._notifyCallback = null; - }; - QuadTree.prototype.load = /** - * Load objects and/or groups into the quad tree, and register notify and processing callbacks. - * - * @param {} objectOrGroup1 Any object that is or extends IGameObject or Group. - * @param {} objectOrGroup2 Any object that is or extends IGameObject or Group. If null, the first parameter will be checked against itself. - * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. - * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). - * @param context The context in which the callbacks will be called - */ - function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { - if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } - if (typeof notifyCallback === "undefined") { notifyCallback = null; } - if (typeof processCallback === "undefined") { processCallback = null; } - if (typeof context === "undefined") { context = null; } - this.add(objectOrGroup1, QuadTree.A_LIST); - if(objectOrGroup2 != null) { - this.add(objectOrGroup2, QuadTree.B_LIST); - QuadTree._useBothLists = true; - } else { - QuadTree._useBothLists = false; - } - QuadTree._notifyCallback = notifyCallback; - QuadTree._processingCallback = processCallback; - QuadTree._callbackContext = context; - }; - QuadTree.prototype.add = /** - * Call this function to add an object to the root of the tree. - * This function will recursively add all group members, but - * not the groups themselves. - * - * @param {} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. - * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. - */ - function (objectOrGroup, list) { - QuadTree._list = list; - if(objectOrGroup.isGroup == true) { - this._i = 0; - this._members = objectOrGroup['members']; - this._l = objectOrGroup['length']; - while(this._i < this._l) { - this._basic = this._members[this._i++]; - if(this._basic != null && this._basic.exists) { - if(this._basic.type == Phaser.Types.GROUP) { - this.add(this._basic, list); - } else { - QuadTree._object = this._basic; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - } - } - } else { - QuadTree._object = objectOrGroup; - if(QuadTree._object.exists && QuadTree._object.allowCollisions) { - this.addObject(); - } - } - }; - QuadTree.prototype.addObject = /** - * Internal function for recursively navigating and creating the tree - * while adding objects to the appropriate nodes. - */ - function () { - //If this quad (not its children) lies entirely inside this object, add it here - if(!this._canSubdivide || ((this._leftEdge >= QuadTree._object.collisionMask.x) && (this._rightEdge <= QuadTree._object.collisionMask.right) && (this._topEdge >= QuadTree._object.collisionMask.y) && (this._bottomEdge <= QuadTree._object.collisionMask.bottom))) { - this.addToList(); - return; - } - //See if the selected object fits completely inside any of the quadrants - if((QuadTree._object.collisionMask.x > this._leftEdge) && (QuadTree._object.collisionMask.right < this._midpointX)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - return; - } - } - if((QuadTree._object.collisionMask.x > this._midpointX) && (QuadTree._object.collisionMask.right < this._rightEdge)) { - if((QuadTree._object.collisionMask.y > this._topEdge) && (QuadTree._object.collisionMask.bottom < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - return; - } - if((QuadTree._object.collisionMask.y > this._midpointY) && (QuadTree._object.collisionMask.bottom < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - return; - } - } - //If it wasn't completely contained we have to check out the partial overlaps - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northWestTree == null) { - this._northWestTree = new QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northWestTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._topEdge) && (QuadTree._object.collisionMask.y < this._midpointY)) { - if(this._northEastTree == null) { - this._northEastTree = new QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); - } - this._northEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._midpointX) && (QuadTree._object.collisionMask.x < this._rightEdge) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southEastTree == null) { - this._southEastTree = new QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southEastTree.addObject(); - } - if((QuadTree._object.collisionMask.right > this._leftEdge) && (QuadTree._object.collisionMask.x < this._midpointX) && (QuadTree._object.collisionMask.bottom > this._midpointY) && (QuadTree._object.collisionMask.y < this._bottomEdge)) { - if(this._southWestTree == null) { - this._southWestTree = new QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); - } - this._southWestTree.addObject(); - } - }; - QuadTree.prototype.addToList = /** - * Internal function for recursively adding objects to leaf lists. - */ - function () { - if(QuadTree._list == QuadTree.A_LIST) { - if(this._tailA.object != null) { - this._ot = this._tailA; - this._tailA = new Phaser.LinkedList(); - this._ot.next = this._tailA; - } - this._tailA.object = QuadTree._object; - } else { - if(this._tailB.object != null) { - this._ot = this._tailB; - this._tailB = new Phaser.LinkedList(); - this._ot.next = this._tailB; - } - this._tailB.object = QuadTree._object; - } - if(!this._canSubdivide) { - return; - } - if(this._northWestTree != null) { - this._northWestTree.addToList(); - } - if(this._northEastTree != null) { - this._northEastTree.addToList(); - } - if(this._southEastTree != null) { - this._southEastTree.addToList(); - } - if(this._southWestTree != null) { - this._southWestTree.addToList(); - } - }; - QuadTree.prototype.execute = /** - * QuadTree's other main function. Call this after adding objects - * using QuadTree.load() to compare the objects that you loaded. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - this._overlapProcessed = false; - if(this._headA.object != null) { - this._iterator = this._headA; - while(this._iterator != null) { - QuadTree._object = this._iterator.object; - if(QuadTree._useBothLists) { - QuadTree._iterator = this._headB; - } else { - QuadTree._iterator = this._iterator.next; - } - if(QuadTree._object.exists && (QuadTree._object.allowCollisions > 0) && (QuadTree._iterator != null) && (QuadTree._iterator.object != null) && QuadTree._iterator.object.exists && this.overlapNode()) { - this._overlapProcessed = true; - } - this._iterator = this._iterator.next; - } - } - //Advance through the tree by calling overlap on each child - if((this._northWestTree != null) && this._northWestTree.execute()) { - this._overlapProcessed = true; - } - if((this._northEastTree != null) && this._northEastTree.execute()) { - this._overlapProcessed = true; - } - if((this._southEastTree != null) && this._southEastTree.execute()) { - this._overlapProcessed = true; - } - if((this._southWestTree != null) && this._southWestTree.execute()) { - this._overlapProcessed = true; - } - return this._overlapProcessed; - }; - QuadTree.prototype.overlapNode = /** - * A private for comparing an object against the contents of a node. - * - * @return {Boolean} Whether or not any overlaps were found. - */ - function () { - //Walk the list and check for overlaps - this._overlapProcessed = false; - while(QuadTree._iterator != null) { - if(!QuadTree._object.exists || (QuadTree._object.allowCollisions <= 0)) { - break; - } - this._checkObject = QuadTree._iterator.object; - if((QuadTree._object === this._checkObject) || !this._checkObject.exists || (this._checkObject.allowCollisions <= 0)) { - QuadTree._iterator = QuadTree._iterator.next; - continue; - } - if(QuadTree._object.collisionMask.checkHullIntersection(this._checkObject.collisionMask)) { - //Execute callback functions if they exist - if((QuadTree._processingCallback == null) || QuadTree._processingCallback(QuadTree._object, this._checkObject)) { - this._overlapProcessed = true; - } - if(this._overlapProcessed && (QuadTree._notifyCallback != null)) { - if(QuadTree._callbackContext !== null) { - QuadTree._notifyCallback.call(QuadTree._callbackContext, QuadTree._object, this._checkObject); - } else { - QuadTree._notifyCallback(QuadTree._object, this._checkObject); - } - } - } - QuadTree._iterator = QuadTree._iterator.next; - } - return this._overlapProcessed; - }; - return QuadTree; - })(Phaser.Rectangle); - Phaser.QuadTree = QuadTree; -})(Phaser || (Phaser = {})); -/// -/// -/** -* Phaser - LinkedList -* -* A miniature linked list class. Useful for optimizing time-critical or highly repetitive tasks! -*/ -var Phaser; -(function (Phaser) { - var LinkedList = (function () { - /** - * Creates a new link, and sets object and next to null. - */ - function LinkedList() { - this.object = null; - this.next = null; - } - LinkedList.prototype.destroy = /** - * Clean up memory. - */ - function () { - this.object = null; - if(this.next != null) { - this.next.destroy(); - } - this.next = null; - }; - return LinkedList; - })(); - Phaser.LinkedList = LinkedList; -})(Phaser || (Phaser = {})); /// /** * Phaser - Line