From e74114f38459a269b5b973c430ab925ef4fedfeb Mon Sep 17 00:00:00 2001 From: Richard Davey Date: Mon, 12 Aug 2013 00:52:35 +0100 Subject: [PATCH] Docs --- Phaser/AnimationManager.js | 138 ++ Phaser/Basic.js | 85 ++ Phaser/Cache.js | 127 ++ Phaser/CameraManager.js | 59 + Phaser/Collision.js | 1198 +++++++++++++++++ Phaser/DynamicTexture.js | 238 ++++ Phaser/FXManager.js | 150 +++ Phaser/GameMath.js | 922 +++++++++++++ Phaser/GameObjectFactory.js | 200 +++ Phaser/Group.js | 598 ++++++++ Phaser/Loader.js | 309 +++++ Phaser/Motion.js | 313 +++++ Phaser/Signal.js | 250 ++++ Phaser/SignalBinding.js | 113 ++ Phaser/SoundManager.js | 85 ++ Phaser/Time.js | 151 +++ Phaser/TweenManager.js | 58 + Phaser/gameobjects/Emitter.js | 285 ++++ Phaser/gameobjects/GameObject.js | 534 ++++++++ Phaser/gameobjects/GeomSprite.js | 449 ++++++ Phaser/gameobjects/Particle.js | 74 + Phaser/gameobjects/Tilemap.js | 314 +++++ Phaser/geom/IntersectResult.js | 45 + Phaser/geom/MicroPoint.js | 134 ++ Phaser/geom/Polygon.js | 47 + Phaser/geom/Quad.js | 109 ++ Phaser/geom/Response.js | 41 + Phaser/system/Camera.js | 353 +++++ Phaser/system/CollisionMask.js | 365 +++++ Phaser/system/LinkedList.js | 30 + Phaser/system/QuadTree.js | 355 +++++ Phaser/system/RandomDataGenerator.js | 227 ++++ Phaser/system/Sound.js | 80 ++ Phaser/system/Tile.js | 123 ++ Phaser/system/TilemapLayer.js | 455 +++++++ Phaser/system/Tween.js | 173 +++ Phaser/system/animation/Animation.js | 107 ++ Phaser/system/animation/AnimationLoader.js | 58 + Phaser/system/animation/Frame.js | 40 + Phaser/system/animation/FrameData.js | 84 ++ Phaser/system/easing/Back.js | 32 + Phaser/system/easing/Bounce.js | 37 + Phaser/system/easing/Circular.js | 29 + Phaser/system/easing/Cubic.js | 29 + Phaser/system/easing/Elastic.js | 68 + Phaser/system/easing/Exponential.js | 35 + Phaser/system/easing/Linear.js | 20 + Phaser/system/easing/Quadratic.js | 29 + Phaser/system/easing/Quartic.js | 29 + Phaser/system/easing/Quintic.js | 29 + Phaser/system/easing/Sinusoidal.js | 26 + Phaser/system/input/Finger.js | 231 ++++ Phaser/system/input/Input.js | 58 + Phaser/system/input/Keyboard.js | 204 +++ Phaser/system/input/Mouse.js | 80 ++ Phaser/system/input/Touch.js | 303 +++++ Phaser/tweens/easing/Back.ts | 35 +- Phaser/tweens/easing/Bounce.ts | 35 +- Phaser/tweens/easing/Cubic.ts | 35 +- Phaser/tweens/easing/Elastic.ts | 35 +- Phaser/tweens/easing/Exponential.ts | 35 +- Phaser/tweens/easing/Linear.ts | 21 +- Phaser/tweens/easing/Quadratic.ts | 35 +- Phaser/tweens/easing/Quartic.ts | 35 +- Phaser/tweens/easing/Quintic.ts | 35 +- Phaser/tweens/easing/Sinusoidal.ts | 35 +- Phaser/utils/CanvasUtils.ts | 87 +- Phaser/utils/CircleUtils.ts | 170 ++- Phaser/utils/ColorUtils.ts | 358 ++--- Phaser/utils/DebugUtils.ts | 100 +- Phaser/utils/PointUtils.ts | 227 ++-- Phaser/utils/RectangleUtils.ts | 137 +- Phaser/utils/SpriteUtils.ts | 147 +- ...gnTimeResolveAssemblyReferencesInput.cache | Bin 0 -> 6226 bytes ...le_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs | 0 ...le_5937a670-0e60-4077-877b-f7221da3dda1.cs | 0 ...le_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs | 0 ...gnTimeResolveAssemblyReferencesInput.cache | Bin 0 -> 6137 bytes ...le_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs | 0 ...le_5937a670-0e60-4077-877b-f7221da3dda1.cs | 0 ...le_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs | 0 81 files changed, 11705 insertions(+), 572 deletions(-) create mode 100644 Phaser/AnimationManager.js create mode 100644 Phaser/Basic.js create mode 100644 Phaser/Cache.js create mode 100644 Phaser/CameraManager.js create mode 100644 Phaser/Collision.js create mode 100644 Phaser/DynamicTexture.js create mode 100644 Phaser/FXManager.js create mode 100644 Phaser/GameMath.js create mode 100644 Phaser/GameObjectFactory.js create mode 100644 Phaser/Group.js create mode 100644 Phaser/Loader.js create mode 100644 Phaser/Motion.js create mode 100644 Phaser/Signal.js create mode 100644 Phaser/SignalBinding.js create mode 100644 Phaser/SoundManager.js create mode 100644 Phaser/Time.js create mode 100644 Phaser/TweenManager.js create mode 100644 Phaser/gameobjects/Emitter.js create mode 100644 Phaser/gameobjects/GameObject.js create mode 100644 Phaser/gameobjects/GeomSprite.js create mode 100644 Phaser/gameobjects/Particle.js create mode 100644 Phaser/gameobjects/Tilemap.js create mode 100644 Phaser/geom/IntersectResult.js create mode 100644 Phaser/geom/MicroPoint.js create mode 100644 Phaser/geom/Polygon.js create mode 100644 Phaser/geom/Quad.js create mode 100644 Phaser/geom/Response.js create mode 100644 Phaser/system/Camera.js create mode 100644 Phaser/system/CollisionMask.js create mode 100644 Phaser/system/LinkedList.js create mode 100644 Phaser/system/QuadTree.js create mode 100644 Phaser/system/RandomDataGenerator.js create mode 100644 Phaser/system/Sound.js create mode 100644 Phaser/system/Tile.js create mode 100644 Phaser/system/TilemapLayer.js create mode 100644 Phaser/system/Tween.js create mode 100644 Phaser/system/animation/Animation.js create mode 100644 Phaser/system/animation/AnimationLoader.js create mode 100644 Phaser/system/animation/Frame.js create mode 100644 Phaser/system/animation/FrameData.js create mode 100644 Phaser/system/easing/Back.js create mode 100644 Phaser/system/easing/Bounce.js create mode 100644 Phaser/system/easing/Circular.js create mode 100644 Phaser/system/easing/Cubic.js create mode 100644 Phaser/system/easing/Elastic.js create mode 100644 Phaser/system/easing/Exponential.js create mode 100644 Phaser/system/easing/Linear.js create mode 100644 Phaser/system/easing/Quadratic.js create mode 100644 Phaser/system/easing/Quartic.js create mode 100644 Phaser/system/easing/Quintic.js create mode 100644 Phaser/system/easing/Sinusoidal.js create mode 100644 Phaser/system/input/Finger.js create mode 100644 Phaser/system/input/Input.js create mode 100644 Phaser/system/input/Keyboard.js create mode 100644 Phaser/system/input/Mouse.js create mode 100644 Phaser/system/input/Touch.js create mode 100644 Plugins/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache create mode 100644 Plugins/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs create mode 100644 Plugins/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs create mode 100644 Plugins/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs create mode 100644 SpecialFX/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache create mode 100644 SpecialFX/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs create mode 100644 SpecialFX/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs create mode 100644 SpecialFX/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs diff --git a/Phaser/AnimationManager.js b/Phaser/AnimationManager.js new file mode 100644 index 00000000..37f1af0e --- /dev/null +++ b/Phaser/AnimationManager.js @@ -0,0 +1,138 @@ +/// +/// +/// +/// +/// +/// +/** +* Phaser - AnimationManager +* +* Any Sprite that has animation contains an instance of the AnimationManager, which is used to add, play and update +* sprite specific animations. +*/ +var Phaser; +(function (Phaser) { + var AnimationManager = (function () { + function AnimationManager(game, parent) { + this._frameData = null; + this.currentFrame = null; + this._game = game; + this._parent = parent; + this._anims = { + }; + } + AnimationManager.prototype.loadFrameData = function (frameData) { + this._frameData = frameData; + this.frame = 0; + }; + AnimationManager.prototype.add = function (name, frames, frameRate, loop, useNumericIndex) { + if (typeof frames === "undefined") { frames = null; } + if (typeof frameRate === "undefined") { frameRate = 60; } + if (typeof loop === "undefined") { loop = false; } + if (typeof useNumericIndex === "undefined") { useNumericIndex = true; } + if(this._frameData == null) { + return; + } + if(frames == null) { + frames = this._frameData.getFrameIndexes(); + } else { + if(this.validateFrames(frames, useNumericIndex) == false) { + throw Error('Invalid frames given to Animation ' + name); + return; + } + } + if(useNumericIndex == false) { + frames = this._frameData.getFrameIndexesByName(frames); + } + this._anims[name] = new Phaser.Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop); + this.currentAnim = this._anims[name]; + this.currentFrame = this.currentAnim.currentFrame; + }; + AnimationManager.prototype.validateFrames = function (frames, useNumericIndex) { + for(var i = 0; i < frames.length; i++) { + if(useNumericIndex == true) { + if(frames[i] > this._frameData.total) { + return false; + } + } else { + if(this._frameData.checkFrameName(frames[i]) == false) { + return false; + } + } + } + return true; + }; + AnimationManager.prototype.play = function (name, frameRate, loop) { + if (typeof frameRate === "undefined") { frameRate = null; } + if(this._anims[name]) { + if(this.currentAnim == this._anims[name]) { + if(this.currentAnim.isPlaying == false) { + this.currentAnim.play(frameRate, loop); + } + } else { + this.currentAnim = this._anims[name]; + this.currentAnim.play(frameRate, loop); + } + } + }; + AnimationManager.prototype.stop = function (name) { + if(this._anims[name]) { + this.currentAnim = this._anims[name]; + this.currentAnim.stop(); + } + }; + AnimationManager.prototype.update = function () { + if(this.currentAnim && this.currentAnim.update() == true) { + this.currentFrame = this.currentAnim.currentFrame; + this._parent.bounds.width = this.currentFrame.width; + this._parent.bounds.height = this.currentFrame.height; + } + }; + Object.defineProperty(AnimationManager.prototype, "frameData", { + get: function () { + return this._frameData; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frameTotal", { + get: function () { + return this._frameData.total; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frame", { + get: function () { + return this._frameIndex; + }, + set: function (value) { + if(this._frameData.getFrame(value) !== null) { + this.currentFrame = this._frameData.getFrame(value); + this._parent.bounds.width = this.currentFrame.width; + this._parent.bounds.height = this.currentFrame.height; + this._frameIndex = value; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(AnimationManager.prototype, "frameName", { + get: function () { + return this.currentFrame.name; + }, + set: function (value) { + if(this._frameData.getFrameByName(value) !== null) { + this.currentFrame = this._frameData.getFrameByName(value); + this._parent.bounds.width = this.currentFrame.width; + this._parent.bounds.height = this.currentFrame.height; + this._frameIndex = this.currentFrame.index; + } + }, + enumerable: true, + configurable: true + }); + return AnimationManager; + })(); + Phaser.AnimationManager = AnimationManager; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Basic.js b/Phaser/Basic.js new file mode 100644 index 00000000..e92fd452 --- /dev/null +++ b/Phaser/Basic.js @@ -0,0 +1,85 @@ +/// +/** +* Phaser - Basic +* +* A useful "generic" object on which all GameObjects and Groups are based. +* It has no size, position or graphical data. +*/ +var Phaser; +(function (Phaser) { + var Basic = (function () { + /** + * Instantiate the basic object. + */ + function Basic(game) { + /** + * Allows you to give this object a name. Useful for debugging, but not actually used internally. + */ + this.name = ''; + this._game = game; + this.ID = -1; + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; + this.isGroup = false; + this.ignoreGlobalUpdate = false; + this.ignoreGlobalRender = false; + this.ignoreDrawDebug = false; + } + Basic.prototype.destroy = /** + * Override this to null out iables or manually call + * destroy() on class members if necessary. + * Don't forget to call super.destroy()! + */ + function () { + }; + Basic.prototype.preUpdate = /** + * Pre-update is called right before update() on each object in the game loop. + */ + function () { + }; + Basic.prototype.update = /** + * Override this to update your class's position and appearance. + * This is where most of your game rules and behavioral code will go. + */ + function (forceUpdate) { + if (typeof forceUpdate === "undefined") { forceUpdate = false; } + }; + Basic.prototype.postUpdate = /** + * Post-update is called right after update() on each object in the game loop. + */ + function () { + }; + Basic.prototype.render = function (camera, cameraOffsetX, cameraOffsetY, forceRender) { + if (typeof forceRender === "undefined") { forceRender = false; } + }; + Basic.prototype.kill = /** + * Handy for "killing" game objects. + * Default behavior is to flag them as nonexistent AND dead. + * However, if you want the "corpse" to remain in the game, + * like to animate an effect or whatever, you should override this, + * setting only alive to false, and leaving exists true. + */ + function () { + this.alive = false; + this.exists = false; + }; + Basic.prototype.revive = /** + * Handy for bringing game objects "back to life". Just sets alive and exists back to true. + * In practice, this is most often called by Object.reset(). + */ + function () { + this.alive = true; + this.exists = true; + }; + Basic.prototype.toString = /** + * Convert object to readable string name. Useful for debugging, save games, etc. + */ + function () { + return ""; + }; + return Basic; + })(); + Phaser.Basic = Basic; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Cache.js b/Phaser/Cache.js new file mode 100644 index 00000000..8b0437d1 --- /dev/null +++ b/Phaser/Cache.js @@ -0,0 +1,127 @@ +/// +/** +* Phaser - Cache +* +* A game only has one instance of a Cache and it is used to store all externally loaded assets such +* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up. +*/ +var Phaser; +(function (Phaser) { + var Cache = (function () { + function Cache(game) { + this._game = game; + this._canvases = { + }; + this._images = { + }; + this._sounds = { + }; + this._text = { + }; + } + Cache.prototype.addCanvas = function (key, canvas, context) { + this._canvases[key] = { + canvas: canvas, + context: context + }; + }; + Cache.prototype.addSpriteSheet = function (key, url, data, frameWidth, frameHeight, frameMax) { + this._images[key] = { + url: url, + data: data, + spriteSheet: true, + frameWidth: frameWidth, + frameHeight: frameHeight + }; + this._images[key].frameData = Phaser.AnimationLoader.parseSpriteSheet(this._game, key, frameWidth, frameHeight, frameMax); + }; + Cache.prototype.addTextureAtlas = function (key, url, data, jsonData) { + this._images[key] = { + url: url, + data: data, + spriteSheet: true + }; + this._images[key].frameData = Phaser.AnimationLoader.parseJSONData(this._game, jsonData); + }; + Cache.prototype.addImage = function (key, url, data) { + this._images[key] = { + url: url, + data: data, + spriteSheet: false + }; + }; + Cache.prototype.addSound = function (key, url, data) { + this._sounds[key] = { + url: url, + data: data, + decoded: false + }; + }; + Cache.prototype.decodedSound = function (key, data) { + this._sounds[key].data = data; + this._sounds[key].decoded = true; + }; + Cache.prototype.addText = function (key, url, data) { + this._text[key] = { + url: url, + data: data + }; + }; + Cache.prototype.getCanvas = function (key) { + if(this._canvases[key]) { + return this._canvases[key].canvas; + } + return null; + }; + Cache.prototype.getImage = function (key) { + if(this._images[key]) { + return this._images[key].data; + } + return null; + }; + Cache.prototype.getFrameData = function (key) { + if(this._images[key] && this._images[key].spriteSheet == true) { + return this._images[key].frameData; + } + return null; + }; + Cache.prototype.getSound = function (key) { + if(this._sounds[key]) { + return this._sounds[key].data; + } + return null; + }; + Cache.prototype.isSoundDecoded = function (key) { + if(this._sounds[key]) { + return this._sounds[key].decoded; + } + }; + Cache.prototype.isSpriteSheet = function (key) { + if(this._images[key]) { + return this._images[key].spriteSheet; + } + }; + Cache.prototype.getText = function (key) { + if(this._text[key]) { + return this._text[key].data; + } + return null; + }; + Cache.prototype.destroy = function () { + for(var item in this._canvases) { + delete this._canvases[item['key']]; + } + for(var item in this._images) { + delete this._images[item['key']]; + } + for(var item in this._sounds) { + delete this._sounds[item['key']]; + } + for(var item in this._text) { + delete this._text[item['key']]; + } + }; + return Cache; + })(); + Phaser.Cache = Cache; +})(Phaser || (Phaser = {})); diff --git a/Phaser/CameraManager.js b/Phaser/CameraManager.js new file mode 100644 index 00000000..26b05ddf --- /dev/null +++ b/Phaser/CameraManager.js @@ -0,0 +1,59 @@ +/// +/// +/** +* Phaser - CameraManager +* +* Your game only has one CameraManager instance and it's responsible for looking after, creating and destroying +* all of the cameras in the world. +* +* TODO: If the Camera is larger than the Stage size then the rotation offset isn't correct +* TODO: Texture Repeat doesn't scroll, because it's part of the camera not the world, need to think about this more +*/ +var Phaser; +(function (Phaser) { + var CameraManager = (function () { + function CameraManager(game, x, y, width, height) { + this._cameraInstance = 0; + this._game = game; + this._cameras = []; + this.current = this.addCamera(x, y, width, height); + } + CameraManager.prototype.getAll = function () { + return this._cameras; + }; + CameraManager.prototype.update = function () { + this._cameras.forEach(function (camera) { + return camera.update(); + }); + }; + CameraManager.prototype.render = function () { + this._cameras.forEach(function (camera) { + return camera.render(); + }); + }; + CameraManager.prototype.addCamera = function (x, y, width, height) { + var newCam = new Phaser.Camera(this._game, this._cameraInstance, x, y, width, height); + this._cameras.push(newCam); + this._cameraInstance++; + return newCam; + }; + CameraManager.prototype.removeCamera = function (id) { + for(var c = 0; c < this._cameras.length; c++) { + if(this._cameras[c].ID == id) { + if(this.current.ID === this._cameras[c].ID) { + this.current = null; + } + this._cameras.splice(c, 1); + return true; + } + } + return false; + }; + CameraManager.prototype.destroy = function () { + this._cameras.length = 0; + this.current = this.addCamera(0, 0, this._game.stage.width, this._game.stage.height); + }; + return CameraManager; + })(); + Phaser.CameraManager = CameraManager; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Collision.js b/Phaser/Collision.js new file mode 100644 index 00000000..c0ac0832 --- /dev/null +++ b/Phaser/Collision.js @@ -0,0 +1,1198 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/** +* Phaser - Collision +* +* A set of extremely useful collision and geometry intersection functions. +*/ +var Phaser; +(function (Phaser) { + var Collision = (function () { + /** + * Collision constructor + * @param game A reference to the current Game + */ + function Collision(game) { + this._game = game; + Collision.T_VECTORS = []; + for(var i = 0; i < 10; i++) { + Collision.T_VECTORS.push(new Vector2()); + } + Collision.T_ARRAYS = []; + for(var i = 0; i < 5; i++) { + Collision.T_ARRAYS.push([]); + } + } + Collision.LEFT = 0x0001; + Collision.RIGHT = 0x0010; + Collision.UP = 0x0100; + Collision.DOWN = 0x1000; + Collision.NONE = 0; + Collision.CEILING = Phaser.Collision.UP; + Collision.FLOOR = Phaser.Collision.DOWN; + Collision.WALL = Phaser.Collision.LEFT | Phaser.Collision.RIGHT; + Collision.ANY = Phaser.Collision.LEFT | Phaser.Collision.RIGHT | Phaser.Collision.UP | Phaser.Collision.DOWN; + Collision.OVERLAP_BIAS = 4; + Collision.TILE_OVERLAP = false; + Collision.lineToLine = /** + * Checks for Line to Line intersection and returns an IntersectResult object containing the results of the intersection. + * @param line1 The first Line object to check + * @param line2 The second Line object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToLine(line1, line2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var denominator = (line1.x1 - line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 - line2.x2); + if(denominator !== 0) { + output.result = true; + output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.x1 - line2.x2) - (line1.x1 - line1.x2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denominator; + output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (line2.y1 - line2.y2) - (line1.y1 - line1.y2) * (line2.x1 * line2.y2 - line2.y1 * line2.x2)) / denominator; + } + return output; + }; + Collision.lineToLineSegment = /** + * Checks for Line to Line Segment intersection and returns an IntersectResult object containing the results of the intersection. + * @param line The Line object to check + * @param seg The Line segment object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToLineSegment(line, seg, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var denominator = (line.x1 - line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 - seg.x2); + if(denominator !== 0) { + output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.x1 - seg.x2) - (line.x1 - line.x2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; + output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (seg.y1 - seg.y2) - (line.y1 - line.y2) * (seg.x1 * seg.y2 - seg.y1 * seg.x2)) / denominator; + var maxX = Math.max(seg.x1, seg.x2); + var minX = Math.min(seg.x1, seg.x2); + var maxY = Math.max(seg.y1, seg.y2); + var minY = Math.min(seg.y1, seg.y2); + if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) { + output.result = true; + } + } + return output; + }; + Collision.lineToRawSegment = /** + * Checks for Line to Raw Line Segment intersection and returns the result in the IntersectResult object. + * @param line The Line object to check + * @param x1 The start x coordinate of the raw segment + * @param y1 The start y coordinate of the raw segment + * @param x2 The end x coordinate of the raw segment + * @param y2 The end y coordinate of the raw segment + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToRawSegment(line, x1, y1, x2, y2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var denominator = (line.x1 - line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 - x2); + if(denominator !== 0) { + output.x = ((line.x1 * line.y2 - line.y1 * line.x2) * (x1 - x2) - (line.x1 - line.x2) * (x1 * y2 - y1 * x2)) / denominator; + output.y = ((line.x1 * line.y2 - line.y1 * line.x2) * (y1 - y2) - (line.y1 - line.y2) * (x1 * y2 - y1 * x2)) / denominator; + var maxX = Math.max(x1, x2); + var minX = Math.min(x1, x2); + var maxY = Math.max(y1, y2); + var minY = Math.min(y1, y2); + if((output.x <= maxX && output.x >= minX) === true || (output.y <= maxY && output.y >= minY) === true) { + output.result = true; + } + } + return output; + }; + Collision.lineToRay = /** + * Checks for Line to Ray intersection and returns the result in an IntersectResult object. + * @param line1 The Line object to check + * @param ray The Ray object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToRay(line1, ray, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var denominator = (line1.x1 - line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 - ray.x2); + if(denominator !== 0) { + output.x = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.x1 - ray.x2) - (line1.x1 - line1.x2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denominator; + output.y = ((line1.x1 * line1.y2 - line1.y1 * line1.x2) * (ray.y1 - ray.y2) - (line1.y1 - line1.y2) * (ray.x1 * ray.y2 - ray.y1 * ray.x2)) / denominator; + output.result = true// true unless either of the 2 following conditions are met + ; + if(!(ray.x1 >= ray.x2) && output.x < ray.x1) { + output.result = false; + } + if(!(ray.y1 >= ray.y2) && output.y < ray.y1) { + output.result = false; + } + } + return output; + }; + Collision.lineToCircle = /** + * Check if the Line and Circle objects intersect + * @param line The Line object to check + * @param circle The Circle object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToCircle(line, circle, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + // Get a perpendicular line running to the center of the circle + if(line.perp(circle.x, circle.y).length <= circle.radius) { + output.result = true; + } + return output; + }; + Collision.lineToRectangle = /** + * Check if the Line intersects each side of the Rectangle + * @param line The Line object to check + * @param rect The Rectangle object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineToRectangle(line, rect, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + // Top of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(line, rect.x, rect.y, rect.right, rect.y, output); + if(output.result === true) { + return output; + } + // Left of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(line, rect.x, rect.y, rect.x, rect.bottom, output); + if(output.result === true) { + return output; + } + // Bottom of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(line, rect.x, rect.bottom, rect.right, rect.bottom, output); + if(output.result === true) { + return output; + } + // Right of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(line, rect.right, rect.y, rect.right, rect.bottom, output); + return output; + }; + Collision.lineSegmentToLineSegment = /** + * Check if the two Line Segments intersect and returns the result in an IntersectResult object. + * @param line1 The first Line Segment to check + * @param line2 The second Line Segment to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineSegmentToLineSegment(line1, line2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + Phaser.Collision.lineToLineSegment(line1, line2); + if(output.result === true) { + if(!(output.x >= Math.min(line1.x1, line1.x2) && output.x <= Math.max(line1.x1, line1.x2) && output.y >= Math.min(line1.y1, line1.y2) && output.y <= Math.max(line1.y1, line1.y2))) { + output.result = false; + } + } + return output; + }; + Collision.lineSegmentToRay = /** + * Check if the Line Segment intersects with the Ray and returns the result in an IntersectResult object. + * @param line The Line Segment to check. + * @param ray The Ray to check. + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineSegmentToRay(line, ray, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + Phaser.Collision.lineToRay(line, ray, output); + if(output.result === true) { + if(!(output.x >= Math.min(line.x1, line.x2) && output.x <= Math.max(line.x1, line.x2) && output.y >= Math.min(line.y1, line.y2) && output.y <= Math.max(line.y1, line.y2))) { + output.result = false; + } + } + return output; + }; + Collision.lineSegmentToCircle = /** + * Check if the Line Segment intersects with the Circle and returns the result in an IntersectResult object. + * @param seg The Line Segment to check. + * @param circle The Circle to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineSegmentToCircle(seg, circle, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var perp = seg.perp(circle.x, circle.y); + if(perp.length <= circle.radius) { + // Line intersects circle - check if segment does + var maxX = Math.max(seg.x1, seg.x2); + var minX = Math.min(seg.x1, seg.x2); + var maxY = Math.max(seg.y1, seg.y2); + var minY = Math.min(seg.y1, seg.y2); + if((perp.x2 <= maxX && perp.x2 >= minX) && (perp.y2 <= maxY && perp.y2 >= minY)) { + output.result = true; + } else { + // Worst case - segment doesn't traverse center, so no perpendicular connection. + if(Phaser.Collision.circleContainsPoint(circle, { + x: seg.x1, + y: seg.y1 + }) || Phaser.Collision.circleContainsPoint(circle, { + x: seg.x2, + y: seg.y2 + })) { + output.result = true; + } + } + } + return output; + }; + Collision.lineSegmentToRectangle = /** + * Check if the Line Segment intersects with the Rectangle and returns the result in an IntersectResult object. + * @param seg The Line Segment to check. + * @param rect The Rectangle to check. + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function lineSegmentToRectangle(seg, rect, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + if(rect.contains(seg.x1, seg.y1) && rect.contains(seg.x2, seg.y2)) { + output.result = true; + } else { + // Top of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(seg, rect.x, rect.y, rect.right, rect.bottom, output); + if(output.result === true) { + return output; + } + // Left of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(seg, rect.x, rect.y, rect.x, rect.bottom, output); + if(output.result === true) { + return output; + } + // Bottom of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(seg, rect.x, rect.bottom, rect.right, rect.bottom, output); + if(output.result === true) { + return output; + } + // Right of the Rectangle vs the Line + Phaser.Collision.lineToRawSegment(seg, rect.right, rect.y, rect.right, rect.bottom, output); + return output; + } + return output; + }; + Collision.rayToRectangle = /** + * Check for Ray to Rectangle intersection and returns the result in an IntersectResult object. + * @param ray The Ray to check. + * @param rect The Rectangle to check. + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function rayToRectangle(ray, rect, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + // Currently just finds first intersection - might not be closest to ray pt1 + Phaser.Collision.lineToRectangle(ray, rect, output); + return output; + }; + Collision.rayToLineSegment = /** + * Check whether a Ray intersects a Line segment and returns the parametric value where the intersection occurs in an IntersectResult object. + * @param rayX1 + * @param rayY1 + * @param rayX2 + * @param rayY2 + * @param lineX1 + * @param lineY1 + * @param lineX2 + * @param lineY2 + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var r; + var s; + var d; + // Check lines are not parallel + if((rayY2 - rayY1) / (rayX2 - rayX1) != (lineY2 - lineY1) / (lineX2 - lineX1)) { + d = (((rayX2 - rayX1) * (lineY2 - lineY1)) - (rayY2 - rayY1) * (lineX2 - lineX1)); + if(d != 0) { + r = (((rayY1 - lineY1) * (lineX2 - lineX1)) - (rayX1 - lineX1) * (lineY2 - lineY1)) / d; + s = (((rayY1 - lineY1) * (rayX2 - rayX1)) - (rayX1 - lineX1) * (rayY2 - rayY1)) / d; + if(r >= 0) { + if(s >= 0 && s <= 1) { + output.result = true; + output.x = rayX1 + r * (rayX2 - rayX1); + output.y = rayY1 + r * (rayY2 - rayY1); + } + } + } + } + return output; + }; + Collision.pointToRectangle = /** + * Determines whether the specified point is contained within the rectangular region defined by the Rectangle object and returns the result in an IntersectResult object. + * @param point The Point or MicroPoint object to check, or any object with x and y properties. + * @param rect The Rectangle object to check the point against + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function pointToRectangle(point, rect, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + output.setTo(point.x, point.y); + output.result = rect.containsPoint(point); + return output; + }; + Collision.rectangleToRectangle = /** + * Check whether two axis aligned Rectangles intersect and returns the intersecting rectangle dimensions in an IntersectResult object if they do. + * @param rect1 The first Rectangle object. + * @param rect2 The second Rectangle object. + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function rectangleToRectangle(rect1, rect2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var leftX = Math.max(rect1.x, rect2.x); + var rightX = Math.min(rect1.right, rect2.right); + var topY = Math.max(rect1.y, rect2.y); + var bottomY = Math.min(rect1.bottom, rect2.bottom); + output.setTo(leftX, topY, rightX - leftX, bottomY - topY, rightX - leftX, bottomY - topY); + var cx = output.x + output.width * .5; + var cy = output.y + output.height * .5; + if((cx > rect1.x && cx < rect1.right) && (cy > rect1.y && cy < rect1.bottom)) { + output.result = true; + } + return output; + }; + Collision.rectangleToCircle = /** + * Checks if the Rectangle and Circle objects intersect and returns the result in an IntersectResult object. + * @param rect The Rectangle object to check + * @param circle The Circle object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function rectangleToCircle(rect, circle, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + return Phaser.Collision.circleToRectangle(circle, rect, output); + }; + Collision.circleToCircle = /** + * Checks if the two Circle objects intersect and returns the result in an IntersectResult object. + * @param circle1 The first Circle object to check + * @param circle2 The second Circle object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function circleToCircle(circle1, circle2, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + output.result = ((circle1.radius + circle2.radius) * (circle1.radius + circle2.radius)) >= Phaser.Collision.distanceSquared(circle1.x, circle1.y, circle2.x, circle2.y); + return output; + }; + Collision.circleToRectangle = /** + * Checks if the Circle object intersects with the Rectangle and returns the result in an IntersectResult object. + * @param circle The Circle object to check + * @param rect The Rectangle object to check + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function circleToRectangle(circle, rect, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + var inflatedRect = rect.clone(); + inflatedRect.inflate(circle.radius, circle.radius); + output.result = inflatedRect.contains(circle.x, circle.y); + return output; + }; + Collision.circleContainsPoint = /** + * Checks if the Point object is contained within the Circle and returns the result in an IntersectResult object. + * @param circle The Circle object to check + * @param point A Point or MicroPoint object to check, or any object with x and y properties + * @param [output] An optional IntersectResult object to store the intersection values in. One is created if none given. + * @returns {IntersectResult=} An IntersectResult object containing the results of the intersection + */ + function circleContainsPoint(circle, point, output) { + if (typeof output === "undefined") { output = new Phaser.IntersectResult(); } + output.result = circle.radius * circle.radius >= Phaser.Collision.distanceSquared(circle.x, circle.y, point.x, point.y); + return output; + }; + Collision.prototype.overlap = /** + * Checks for overlaps between two objects using the world QuadTree. Can be GameObject vs. GameObject, GameObject vs. Group or Group vs. Group. + * Note: Does not take the objects scrollFactor into account. All overlaps are check in world space. + * @param object1 The first GameObject or Group to check. If null the world.group is used. + * @param object2 The second GameObject or Group to check. + * @param notifyCallback A callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. + * @param processCallback A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then notifyCallback will only be called if processCallback returns true. + * @param context The context in which the callbacks will be called + * @returns {boolean} true if the objects overlap, otherwise false. + */ + function (object1, object2, notifyCallback, processCallback, context) { + if (typeof object1 === "undefined") { object1 = null; } + if (typeof object2 === "undefined") { object2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof processCallback === "undefined") { processCallback = null; } + if (typeof context === "undefined") { context = null; } + if(object1 == null) { + object1 = this._game.world.group; + } + if(object2 == object1) { + object2 = null; + } + Phaser.QuadTree.divisions = this._game.world.worldDivisions; + var quadTree = new Phaser.QuadTree(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height); + quadTree.load(object1, object2, notifyCallback, processCallback, context); + var result = quadTree.execute(); + quadTree.destroy(); + quadTree = null; + return result; + }; + Collision.separate = /** + * The core Collision separation function used by Collision.overlap. + * @param object1 The first GameObject to separate + * @param object2 The second GameObject to separate + * @returns {boolean} Returns true if the objects were separated, otherwise false. + */ + function separate(object1, object2) { + object1.collisionMask.update(); + object2.collisionMask.update(); + var separatedX = Phaser.Collision.separateX(object1, object2); + var separatedY = Phaser.Collision.separateY(object1, object2); + return separatedX || separatedY; + }; + Collision.separateTile = /** + * Collision resolution specifically for GameObjects vs. Tiles. + * @param object The GameObject to separate + * @param tile The Tile to separate + * @returns {boolean} Whether the objects in fact touched and were separated + */ + function separateTile(object, x, y, width, height, mass, collideLeft, collideRight, collideUp, collideDown, separateX, separateY) { + object.collisionMask.update(); + var separatedX = Phaser.Collision.separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separateX); + var separatedY = Phaser.Collision.separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separateY); + return separatedX || separatedY; + }; + Collision.separateTileX = /** + * Separates the two objects on their x axis + * @param object The GameObject to separate + * @param tile The Tile to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. + */ + function separateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separate) { + // Can't separate two immovable objects (tiles are always immovable) + if(object.immovable) { + return false; + } + // First, get the object delta + var overlap = 0; + var objDelta = object.x - object.last.x; + //var objDelta: number = object.collisionMask.deltaX; + if(objDelta != 0) { + // Check if the X hulls actually overlap + var objDeltaAbs = (objDelta > 0) ? objDelta : -objDelta; + //var objDeltaAbs: number = object.collisionMask.deltaXAbs; + var objBounds = new Phaser.Quad(object.x - ((objDelta > 0) ? objDelta : 0), object.last.y, object.width + ((objDelta > 0) ? objDelta : -objDelta), object.height); + if((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) { + var maxOverlap = objDeltaAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(objDelta > 0) { + overlap = object.x + object.width - x; + if((overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.RIGHT) || collideLeft == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.RIGHT; + } + } else if(objDelta < 0) { + overlap = object.x - width - x; + if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.LEFT) || collideRight == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.LEFT; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + if(separate == true) { + //console.log(' + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + Phaser.Collision.TILE_OVERLAP = true; + return true; + } else { + return false; + } + }; + Collision.separateTileY = /** + * Separates the two objects on their y axis + * @param object The first GameObject to separate + * @param tile The second GameObject to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. + */ + function separateTileY(object, x, y, width, height, mass, collideUp, collideDown, separate) { + // Can't separate two immovable objects (tiles are always immovable) + if(object.immovable) { + return false; + } + // First, get the two object deltas + var overlap = 0; + var objDelta = object.y - object.last.y; + if(objDelta != 0) { + // Check if the Y hulls actually overlap + var objDeltaAbs = (objDelta > 0) ? objDelta : -objDelta; + var objBounds = new Phaser.Quad(object.x, object.y - ((objDelta > 0) ? objDelta : 0), object.width, object.height + objDeltaAbs); + if((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) { + var maxOverlap = objDeltaAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(objDelta > 0) { + overlap = object.y + object.height - y; + if((overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.DOWN) || collideUp == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.DOWN; + } + } else if(objDelta < 0) { + overlap = object.y - height - y; + if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.UP) || collideDown == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.UP; + } + } + } + } + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + if(separate == true) { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + Phaser.Collision.TILE_OVERLAP = true; + return true; + } else { + return false; + } + }; + Collision.NEWseparateTileX = /** + * Separates the two objects on their x axis + * @param object The GameObject to separate + * @param tile The Tile to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. + */ + function NEWseparateTileX(object, x, y, width, height, mass, collideLeft, collideRight, separate) { + // Can't separate two immovable objects (tiles are always immovable) + if(object.immovable) { + return false; + } + // First, get the object delta + var overlap = 0; + if(object.collisionMask.deltaX != 0) { + // Check if the X hulls actually overlap + //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //var objBounds: Quad = new Quad(object.x - ((objDelta > 0) ? objDelta : 0), object.last.y, object.width + ((objDelta > 0) ? objDelta : -objDelta), object.height); + //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) + if(object.collisionMask.intersectsRaw(x, x + width, y, y + height)) { + var maxOverlap = object.collisionMask.deltaXAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(object.collisionMask.deltaX > 0) { + //overlap = object.x + object.width - x; + overlap = object.collisionMask.right - x; + if((overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.RIGHT) || collideLeft == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.RIGHT; + } + } else if(object.collisionMask.deltaX < 0) { + //overlap = object.x - width - x; + overlap = object.collisionMask.x - width - x; + if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.LEFT) || collideRight == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.LEFT; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + if(separate == true) { + object.x = object.x - overlap; + object.velocity.x = -(object.velocity.x * object.elasticity); + } + Phaser.Collision.TILE_OVERLAP = true; + return true; + } else { + return false; + } + }; + Collision.NEWseparateTileY = /** + * Separates the two objects on their y axis + * @param object The first GameObject to separate + * @param tile The second GameObject to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. + */ + function NEWseparateTileY(object, x, y, width, height, mass, collideUp, collideDown, separate) { + // Can't separate two immovable objects (tiles are always immovable) + if(object.immovable) { + return false; + } + // First, get the two object deltas + var overlap = 0; + //var objDelta: number = object.y - object.last.y; + if(object.collisionMask.deltaY != 0) { + // Check if the Y hulls actually overlap + //var objDeltaAbs: number = (objDelta > 0) ? objDelta : -objDelta; + //var objBounds: Quad = new Quad(object.x, object.y - ((objDelta > 0) ? objDelta : 0), object.width, object.height + objDeltaAbs); + //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) + if(object.collisionMask.intersectsRaw(x, x + width, y, y + height)) { + //var maxOverlap: number = objDeltaAbs + Collision.OVERLAP_BIAS; + var maxOverlap = object.collisionMask.deltaYAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(object.collisionMask.deltaY > 0) { + //overlap = object.y + object.height - y; + overlap = object.collisionMask.bottom - y; + if((overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.DOWN) || collideUp == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.DOWN; + } + } else if(object.collisionMask.deltaY < 0) { + //overlap = object.y - height - y; + overlap = object.collisionMask.y - height - y; + if((-overlap > maxOverlap) || !(object.allowCollisions & Phaser.Collision.UP) || collideDown == false) { + overlap = 0; + } else { + object.touching |= Phaser.Collision.UP; + } + } + } + } + // TODO - with super low velocities you get lots of stuttering, set some kind of base minimum here + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + if(separate == true) { + object.y = object.y - overlap; + object.velocity.y = -(object.velocity.y * object.elasticity); + } + Phaser.Collision.TILE_OVERLAP = true; + return true; + } else { + return false; + } + }; + Collision.separateX = /** + * Separates the two objects on their x axis + * @param object1 The first GameObject to separate + * @param object2 The second GameObject to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the X axis. + */ + function separateX(object1, object2) { + // Can't separate two immovable objects + if(object1.immovable && object2.immovable) { + return false; + } + // First, get the two object deltas + var overlap = 0; + if(object1.collisionMask.deltaX != object2.collisionMask.deltaX) { + if(object1.collisionMask.intersects(object2.collisionMask)) { + var maxOverlap = object1.collisionMask.deltaXAbs + object2.collisionMask.deltaXAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(object1.collisionMask.deltaX > object2.collisionMask.deltaX) { + overlap = object1.collisionMask.right - object2.collisionMask.x; + if((overlap > maxOverlap) || !(object1.allowCollisions & Phaser.Collision.RIGHT) || !(object2.allowCollisions & Phaser.Collision.LEFT)) { + overlap = 0; + } else { + object1.touching |= Phaser.Collision.RIGHT; + object2.touching |= Phaser.Collision.LEFT; + } + } else if(object1.collisionMask.deltaX < object2.collisionMask.deltaX) { + overlap = object1.collisionMask.x - object2.collisionMask.width - object2.collisionMask.x; + if((-overlap > maxOverlap) || !(object1.allowCollisions & Phaser.Collision.LEFT) || !(object2.allowCollisions & Phaser.Collision.RIGHT)) { + overlap = 0; + } else { + object1.touching |= Phaser.Collision.LEFT; + object2.touching |= Phaser.Collision.RIGHT; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + var obj1Velocity = object1.velocity.x; + var obj2Velocity = object2.velocity.x; + if(!object1.immovable && !object2.immovable) { + overlap *= 0.5; + object1.x = object1.x - overlap; + object2.x += overlap; + var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); + var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); + var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; + obj1NewVelocity -= average; + obj2NewVelocity -= average; + object1.velocity.x = average + obj1NewVelocity * object1.elasticity; + object2.velocity.x = average + obj2NewVelocity * object2.elasticity; + } else if(!object1.immovable) { + object1.x = object1.x - overlap; + object1.velocity.x = obj2Velocity - obj1Velocity * object1.elasticity; + } else if(!object2.immovable) { + object2.x += overlap; + object2.velocity.x = obj1Velocity - obj2Velocity * object2.elasticity; + } + return true; + } else { + return false; + } + }; + Collision.separateY = /** + * Separates the two objects on their y axis + * @param object1 The first GameObject to separate + * @param object2 The second GameObject to separate + * @returns {boolean} Whether the objects in fact touched and were separated along the Y axis. + */ + function separateY(object1, object2) { + // Can't separate two immovable objects + if(object1.immovable && object2.immovable) { + return false; + } + // First, get the two object deltas + var overlap = 0; + if(object1.collisionMask.deltaY != object2.collisionMask.deltaY) { + if(object1.collisionMask.intersects(object2.collisionMask)) { + // This is the only place to use the DeltaAbs values + var maxOverlap = object1.collisionMask.deltaYAbs + object2.collisionMask.deltaYAbs + Phaser.Collision.OVERLAP_BIAS; + // If they did overlap (and can), figure out by how much and flip the corresponding flags + if(object1.collisionMask.deltaY > object2.collisionMask.deltaY) { + overlap = object1.collisionMask.bottom - object2.collisionMask.y; + if((overlap > maxOverlap) || !(object1.allowCollisions & Phaser.Collision.DOWN) || !(object2.allowCollisions & Phaser.Collision.UP)) { + overlap = 0; + } else { + object1.touching |= Phaser.Collision.DOWN; + object2.touching |= Phaser.Collision.UP; + } + } else if(object1.collisionMask.deltaY < object2.collisionMask.deltaY) { + overlap = object1.collisionMask.y - object2.collisionMask.height - object2.collisionMask.y; + if((-overlap > maxOverlap) || !(object1.allowCollisions & Phaser.Collision.UP) || !(object2.allowCollisions & Phaser.Collision.DOWN)) { + overlap = 0; + } else { + object1.touching |= Phaser.Collision.UP; + object2.touching |= Phaser.Collision.DOWN; + } + } + } + } + // Then adjust their positions and velocities accordingly (if there was any overlap) + if(overlap != 0) { + var obj1Velocity = object1.velocity.y; + var obj2Velocity = object2.velocity.y; + if(!object1.immovable && !object2.immovable) { + overlap *= 0.5; + object1.y = object1.y - overlap; + object2.y += overlap; + var obj1NewVelocity = Math.sqrt((obj2Velocity * obj2Velocity * object2.mass) / object1.mass) * ((obj2Velocity > 0) ? 1 : -1); + var obj2NewVelocity = Math.sqrt((obj1Velocity * obj1Velocity * object1.mass) / object2.mass) * ((obj1Velocity > 0) ? 1 : -1); + var average = (obj1NewVelocity + obj2NewVelocity) * 0.5; + obj1NewVelocity -= average; + obj2NewVelocity -= average; + object1.velocity.y = average + obj1NewVelocity * object1.elasticity; + object2.velocity.y = average + obj2NewVelocity * object2.elasticity; + } else if(!object1.immovable) { + object1.y = object1.y - overlap; + object1.velocity.y = obj2Velocity - obj1Velocity * object1.elasticity; + // This is special case code that handles things like horizontal moving platforms you can ride + if(object2.active && object2.moves && (object1.collisionMask.deltaY > object2.collisionMask.deltaY)) { + object1.x += object2.x - object2.last.x; + } + } else if(!object2.immovable) { + object2.y += overlap; + object2.velocity.y = obj1Velocity - obj2Velocity * object2.elasticity; + // This is special case code that handles things like horizontal moving platforms you can ride + if(object1.active && object1.moves && (object1.collisionMask.deltaY < object2.collisionMask.deltaY)) { + object2.x += object1.x - object1.last.x; + } + } + return true; + } else { + return false; + } + }; + Collision.distance = /** + * Returns the distance between the two given coordinates. + * @param x1 The X value of the first coordinate + * @param y1 The Y value of the first coordinate + * @param x2 The X value of the second coordinate + * @param y2 The Y value of the second coordinate + * @returns {number} The distance between the two coordinates + */ + function distance(x1, y1, x2, y2) { + return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + }; + Collision.distanceSquared = /** + * Returns the distanced squared between the two given coordinates. + * @param x1 The X value of the first coordinate + * @param y1 The Y value of the first coordinate + * @param x2 The X value of the second coordinate + * @param y2 The Y value of the second coordinate + * @returns {number} The distance between the two coordinates + */ + function distanceSquared(x1, y1, x2, y2) { + return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); + }; + Collision.flattenPointsOn = // SAT + /** + * Flattens the specified array of points onto a unit vector axis, + * resulting in a one dimensional range of the minimum and + * maximum value on that axis. + * + * @param {Array.} points The points to flatten. + * @param {Vector} normal The unit vector axis to flatten on. + * @param {Array.} result An array. After calling this function, + * result[0] will be the minimum value, + * result[1] will be the maximum value. + */ + function flattenPointsOn(points, normal, result) { + var min = Number.MAX_VALUE; + var max = -Number.MAX_VALUE; + var len = points.length; + for(var i = 0; i < len; i++) { + // Get the magnitude of the projection of the point onto the normal + var dot = points[i].dot(normal); + if(dot < min) { + min = dot; + } + if(dot > max) { + max = dot; + } + } + result[0] = min; + result[1] = max; + }; + Collision.isSeparatingAxis = /** + * Check whether two convex clockwise polygons are separated by the specified + * axis (must be a unit vector). + * + * @param {Vector} aPos The position of the first polygon. + * @param {Vector} bPos The position of the second polygon. + * @param {Array.} aPoints The points in the first polygon. + * @param {Array.} bPoints The points in the second polygon. + * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons + * will be projected onto this axis. + * @param {Response=} response A Response object (optional) which will be populated + * if the axis is not a separating axis. + * @return {boolean} true if it is a separating axis, false otherwise. If false, + * and a response is passed in, information about how much overlap and + * the direction of the overlap will be populated. + */ + function isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response) { + if (typeof response === "undefined") { response = null; } + var rangeA = Phaser.Collision.T_ARRAYS.pop(); + var rangeB = Phaser.Collision.T_ARRAYS.pop(); + // Get the magnitude of the offset between the two polygons + var offsetV = Phaser.Collision.T_VECTORS.pop().copyFrom(bPos).sub(aPos); + var projectedOffset = offsetV.dot(axis); + // Project the polygons onto the axis. + Phaser.Collision.flattenPointsOn(aPoints, axis, rangeA); + Phaser.Collision.flattenPointsOn(bPoints, axis, rangeB); + // Move B's range to its position relative to A. + rangeB[0] += projectedOffset; + rangeB[1] += projectedOffset; + // Check if there is a gap. If there is, this is a separating axis and we can stop + if(rangeA[0] > rangeB[1] || rangeB[0] > rangeA[1]) { + Phaser.Collision.T_VECTORS.push(offsetV); + Phaser.Collision.T_ARRAYS.push(rangeA); + Phaser.Collision.T_ARRAYS.push(rangeB); + return true; + } + // If we're calculating a response, calculate the overlap. + if(response) { + var overlap = 0; + // A starts further left than B + if(rangeA[0] < rangeB[0]) { + response.aInB = false; + // A ends before B does. We have to pull A out of B + if(rangeA[1] < rangeB[1]) { + overlap = rangeA[1] - rangeB[0]; + response.bInA = false; + // B is fully inside A. Pick the shortest way out. + } else { + var option1 = rangeA[1] - rangeB[0]; + var option2 = rangeB[1] - rangeA[0]; + overlap = option1 < option2 ? option1 : -option2; + } + // B starts further left than A + } else { + response.bInA = false; + // B ends before A ends. We have to push A out of B + if(rangeA[1] > rangeB[1]) { + overlap = rangeA[0] - rangeB[1]; + response.aInB = false; + // A is fully inside B. Pick the shortest way out. + } else { + var option1 = rangeA[1] - rangeB[0]; + var option2 = rangeB[1] - rangeA[0]; + overlap = option1 < option2 ? option1 : -option2; + } + } + // If this is the smallest amount of overlap we've seen so far, set it as the minimum overlap. + var absOverlap = Math.abs(overlap); + if(absOverlap < response.overlap) { + response.overlap = absOverlap; + response.overlapN.copyFrom(axis); + if(overlap < 0) { + response.overlapN.reverse(); + } + } + } + Phaser.Collision.T_VECTORS.push(offsetV); + Phaser.Collision.T_ARRAYS.push(rangeA); + Phaser.Collision.T_ARRAYS.push(rangeB); + return false; + }; + Collision.LEFT_VORNOI_REGION = -1; + Collision.MIDDLE_VORNOI_REGION = 0; + Collision.RIGHT_VORNOI_REGION = 1; + Collision.vornoiRegion = /** + * Calculates which Vornoi region a point is on a line segment. + * It is assumed that both the line and the point are relative to (0, 0) + * + * | (0) | + * (-1) [0]--------------[1] (1) + * | (0) | + * + * @param {Vector} line The line segment. + * @param {Vector} point The point. + * @return {number} LEFT_VORNOI_REGION (-1) if it is the left region, + * MIDDLE_VORNOI_REGION (0) if it is the middle region, + * RIGHT_VORNOI_REGION (1) if it is the right region. + */ + function vornoiRegion(line, point) { + var len2 = line.length2(); + var dp = point.dot(line); + if(dp < 0) { + return Phaser.Collision.LEFT_VORNOI_REGION; + } else if(dp > len2) { + return Phaser.Collision.RIGHT_VORNOI_REGION; + } else { + return Phaser.Collision.MIDDLE_VORNOI_REGION; + } + }; + Collision.testCircleCircle = /** + * Check if two circles intersect. + * + * @param {Circle} a The first circle. + * @param {Circle} b The second circle. + * @param {Response=} response Response object (optional) that will be populated if + * the circles intersect. + * @return {boolean} true if the circles intersect, false if they don't. + */ + function testCircleCircle(a, b, response) { + if (typeof response === "undefined") { response = null; } + var differenceV = Phaser.Collision.T_VECTORS.pop().copyFrom(b.pos).sub(a.pos); + var totalRadius = a.radius + b.radius; + var totalRadiusSq = totalRadius * totalRadius; + var distanceSq = differenceV.length2(); + if(distanceSq > totalRadiusSq) { + // They do not intersect + Phaser.Collision.T_VECTORS.push(differenceV); + return false; + } + // They intersect. If we're calculating a response, calculate the overlap. + if(response) { + var dist = Math.sqrt(distanceSq); + response.a = a; + response.b = b; + response.overlap = totalRadius - dist; + response.overlapN.copyFrom(differenceV.normalize()); + response.overlapV.copyFrom(differenceV).scale(response.overlap); + response.aInB = a.radius <= b.radius && dist <= b.radius - a.radius; + response.bInA = b.radius <= a.radius && dist <= a.radius - b.radius; + } + Phaser.Collision.T_VECTORS.push(differenceV); + return true; + }; + Collision.testPolygonCircle = /** + * Check if a polygon and a circle intersect. + * + * @param {Polygon} polygon The polygon. + * @param {Circle} circle The circle. + * @param {Response=} response Response object (optional) that will be populated if + * they interset. + * @return {boolean} true if they intersect, false if they don't. + */ + function testPolygonCircle(polygon, circle, response) { + if (typeof response === "undefined") { response = null; } + var circlePos = Phaser.Collision.T_VECTORS.pop().copyFrom(circle.pos).sub(polygon.pos); + var radius = circle.radius; + var radius2 = radius * radius; + var points = polygon.points; + var len = points.length; + var edge = Collision.T_VECTORS.pop(); + var point = Collision.T_VECTORS.pop(); + // For each edge in the polygon + for(var i = 0; i < len; i++) { + var next = i === len - 1 ? 0 : i + 1; + var prev = i === 0 ? len - 1 : i - 1; + var overlap = 0; + var overlapN = null; + // Get the edge + edge.copyFrom(polygon.edges[i]); + // Calculate the center of the cirble relative to the starting point of the edge + point.copyFrom(circlePos).sub(points[i]); + // If the distance between the center of the circle and the point + // is bigger than the radius, the polygon is definitely not fully in + // the circle. + if(response && point.length2() > radius2) { + response.aInB = false; + } + // Calculate which Vornoi region the center of the circle is in. + var region = Collision.vornoiRegion(edge, point); + if(region === Phaser.Collision.LEFT_VORNOI_REGION) { + // Need to make sure we're in the RIGHT_VORNOI_REGION of the previous edge. + edge.copyFrom(polygon.edges[prev]); + // Calculate the center of the circle relative the starting point of the previous edge + var point2 = Phaser.Collision.T_VECTORS.pop().copyFrom(circlePos).sub(points[prev]); + region = Collision.vornoiRegion(edge, point2); + if(region === Phaser.Collision.RIGHT_VORNOI_REGION) { + // It's in the region we want. Check if the circle intersects the point. + var dist = point.length2(); + if(dist > radius) { + // No intersection + Phaser.Collision.T_VECTORS.push(circlePos); + Phaser.Collision.T_VECTORS.push(edge); + Phaser.Collision.T_VECTORS.push(point); + Phaser.Collision.T_VECTORS.push(point2); + return false; + } else if(response) { + // It intersects, calculate the overlap + response.bInA = false; + overlapN = point.normalize(); + overlap = radius - dist; + } + } + Phaser.Collision.T_VECTORS.push(point2); + } else if(region === Phaser.Collision.RIGHT_VORNOI_REGION) { + // Need to make sure we're in the left region on the next edge + edge.copyFrom(polygon.edges[next]); + // Calculate the center of the circle relative to the starting point of the next edge + point.copyFrom(circlePos).sub(points[next]); + region = Collision.vornoiRegion(edge, point); + if(region === Phaser.Collision.LEFT_VORNOI_REGION) { + // It's in the region we want. Check if the circle intersects the point. + var dist = point.length2(); + if(dist > radius) { + // No intersection + Phaser.Collision.T_VECTORS.push(circlePos); + Phaser.Collision.T_VECTORS.push(edge); + Phaser.Collision.T_VECTORS.push(point); + return false; + } else if(response) { + // It intersects, calculate the overlap + response.bInA = false; + overlapN = point.normalize(); + overlap = radius - dist; + } + } + // MIDDLE_VORNOI_REGION + } else { + // Need to check if the circle is intersecting the edge, + // Change the edge into its "edge normal". + var normal = edge.perp().normalize(); + // Find the perpendicular distance between the center of the + // circle and the edge. + var dist = point.dot(normal); + var distAbs = Math.abs(dist); + // If the circle is on the outside of the edge, there is no intersection + if(dist > 0 && distAbs > radius) { + Phaser.Collision.T_VECTORS.push(circlePos); + Phaser.Collision.T_VECTORS.push(normal); + Phaser.Collision.T_VECTORS.push(point); + return false; + } else if(response) { + // It intersects, calculate the overlap. + overlapN = normal; + overlap = radius - dist; + // If the center of the circle is on the outside of the edge, or part of the + // circle is on the outside, the circle is not fully inside the polygon. + if(dist >= 0 || overlap < 2 * radius) { + response.bInA = false; + } + } + } + // If this is the smallest overlap we've seen, keep it. + // (overlapN may be null if the circle was in the wrong Vornoi region) + if(overlapN && response && 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); + } + Phaser.Collision.T_VECTORS.push(circlePos); + Phaser.Collision.T_VECTORS.push(edge); + Phaser.Collision.T_VECTORS.push(point); + return true; + }; + Collision.testCirclePolygon = /** + * Check if a circle and a polygon intersect. + * + * NOTE: This runs slightly slower than polygonCircle as it just + * runs polygonCircle and reverses everything at the end. + * + * @param {Circle} circle The circle. + * @param {Polygon} polygon The polygon. + * @param {Response=} response Response object (optional) that will be populated if + * they interset. + * @return {boolean} true if they intersect, false if they don't. + */ + function testCirclePolygon(circle, polygon, response) { + if (typeof response === "undefined") { response = null; } + var result = Phaser.Collision.testPolygonCircle(polygon, circle, response); + if(result && response) { + // Swap A and B in the response. + var a = response.a; + var aInB = response.aInB; + response.overlapN.reverse(); + response.overlapV.reverse(); + response.a = response.b; + response.b = a; + response.aInB = response.bInA; + response.bInA = aInB; + } + return result; + }; + Collision.testPolygonPolygon = /** + * Checks whether two convex, clockwise polygons intersect. + * + * @param {Polygon} a The first polygon. + * @param {Polygon} b The second polygon. + * @param {Response=} response Response object (optional) that will be populated if + * they interset. + * @return {boolean} true if they intersect, false if they don't. + */ + function testPolygonPolygon(a, b, response) { + if (typeof response === "undefined") { response = null; } + var aPoints = a.points; + var aLen = aPoints.length; + var bPoints = b.points; + var bLen = bPoints.length; + // If any of the edge normals of A is a separating axis, no intersection. + for(var i = 0; i < aLen; i++) { + if(Phaser.Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, a.normals[i], response)) { + return false; + } + } + // If any of the edge normals of B is a separating axis, no intersection. + for(var i = 0; i < bLen; i++) { + if(Phaser.Collision.isSeparatingAxis(a.pos, b.pos, aPoints, bPoints, b.normals[i], response)) { + return false; + } + } + // Since none of the edge normals of A or B are a separating axis, there is an intersection + // and we've already calculated the smallest overlap (in isSeparatingAxis). Calculate the + // final overlap vector. + if(response) { + response.a = a; + response.b = b; + response.overlapV.copyFrom(response.overlapN).scale(response.overlap); + } + return true; + }; + return Collision; + })(); + Phaser.Collision = Collision; +})(Phaser || (Phaser = {})); diff --git a/Phaser/DynamicTexture.js b/Phaser/DynamicTexture.js new file mode 100644 index 00000000..7123d966 --- /dev/null +++ b/Phaser/DynamicTexture.js @@ -0,0 +1,238 @@ +/// +/** +* Phaser - DynamicTexture +* +* A DynamicTexture can be thought of as a mini canvas into which you can draw anything. +* Game Objects can be assigned a DynamicTexture, so when they render in the world they do so +* based on the contents of the texture at the time. This allows you to create powerful effects +* once and have them replicated across as many game objects as you like. +*/ +var Phaser; +(function (Phaser) { + var DynamicTexture = (function () { + /** + * DynamicTexture constructor + * Create a new DynamicTexture. + * + * @param game {Phaser.Game} Current game instance. + * @param width {number} Init width of this texture. + * @param height {number} Init height of this texture. + */ + function DynamicTexture(game, width, height) { + this._sx = 0; + this._sy = 0; + this._sw = 0; + this._sh = 0; + this._dx = 0; + this._dy = 0; + this._dw = 0; + this._dh = 0; + this._game = game; + this.canvas = document.createElement('canvas'); + this.canvas.width = width; + this.canvas.height = height; + this.context = this.canvas.getContext('2d'); + this.bounds = new Rectangle(0, 0, width, height); + } + DynamicTexture.prototype.getPixel = /** + * Get a color of a specific pixel. + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return {number} A native color value integer (format: 0xRRGGBB) + */ + function (x, y) { + //r = imageData.data[0]; + //g = imageData.data[1]; + //b = imageData.data[2]; + //a = imageData.data[3]; + var imageData = this.context.getImageData(x, y, 1, 1); + return this.getColor(imageData.data[0], imageData.data[1], imageData.data[2]); + }; + DynamicTexture.prototype.getPixel32 = /** + * Get a color of a specific pixel (including alpha value). + * @param x {number} X position of the pixel in this texture. + * @param y {number} Y position of the pixel in this texture. + * @return A native color value integer (format: 0xAARRGGBB) + */ + function (x, y) { + var imageData = this.context.getImageData(x, y, 1, 1); + return this.getColor32(imageData.data[3], imageData.data[0], imageData.data[1], imageData.data[2]); + }; + DynamicTexture.prototype.getPixels = /** + * Get pixels in array in a specific rectangle. + * @param rect {Rectangle} The specific rectangle. + * @returns {array} CanvasPixelArray. + */ + function (rect) { + return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); + }; + DynamicTexture.prototype.setPixel = /** + * Set color of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xRRGGBB) + */ + function (x, y, color) { + this.context.fillStyle = color; + this.context.fillRect(x, y, 1, 1); + }; + DynamicTexture.prototype.setPixel32 = /** + * Set color (with alpha) of a specific pixel. + * @param x {number} X position of the target pixel. + * @param y {number} Y position of the target pixel. + * @param color {number} Native integer with color value. (format: 0xAARRGGBB) + */ + function (x, y, color) { + this.context.fillStyle = color; + this.context.fillRect(x, y, 1, 1); + }; + DynamicTexture.prototype.setPixels = /** + * Set image data to a specific rectangle. + * @param rect {Rectangle} Target rectangle. + * @param input {object} Source image data. + */ + function (rect, input) { + this.context.putImageData(input, rect.x, rect.y); + }; + DynamicTexture.prototype.fillRect = /** + * Fill a given rectangle with specific color. + * @param rect {Rectangle} Target rectangle you want to fill. + * @param color {number} A native number with color value. (format: 0xRRGGBB) + */ + function (rect, color) { + this.context.fillStyle = color; + this.context.fillRect(rect.x, rect.y, rect.width, rect.height); + }; + DynamicTexture.prototype.pasteImage = /** + * + */ + function (key, frame, destX, destY, destWidth, destHeight) { + if (typeof frame === "undefined") { frame = -1; } + if (typeof destX === "undefined") { destX = 0; } + if (typeof destY === "undefined") { destY = 0; } + if (typeof destWidth === "undefined") { destWidth = null; } + if (typeof destHeight === "undefined") { destHeight = null; } + var texture = null; + var frameData; + this._sx = 0; + this._sy = 0; + this._dx = destX; + this._dy = destY; + // TODO - Load a frame from a sprite sheet, otherwise we'll draw the whole lot + if(frame > -1) { + //if (this._game.cache.isSpriteSheet(key)) + //{ + // texture = this._game.cache.getImage(key); + //this.animations.loadFrameData(this._game.cache.getFrameData(key)); + //} + } else { + texture = this._game.cache.getImage(key); + this._sw = texture.width; + this._sh = texture.height; + this._dw = texture.width; + this._dh = texture.height; + } + if(destWidth !== null) { + this._dw = destWidth; + } + if(destHeight !== null) { + this._dh = destHeight; + } + if(texture != null) { + this.context.drawImage(texture, // Source Image + this._sx, // Source X (location within the source image) + this._sy, // Source Y + this._sw, // Source Width + this._sh, // Source Height + this._dx, // Destination X (where on the canvas it'll be drawn) + this._dy, // Destination Y + this._dw, // Destination Width (always same as Source Width unless scaled) + this._dh); + // Destination Height (always same as Source Height unless scaled) + } + }; + DynamicTexture.prototype.copyPixels = // TODO - Add in support for: alphaBitmapData: BitmapData = null, alphaPoint: Point = null, mergeAlpha: bool = false + /** + * Copy pixel from another DynamicTexture to this texture. + * @param sourceTexture {DynamicTexture} Source texture object. + * @param sourceRect {Rectangle} The specific region rectangle to be copied to this in the source. + * @param destPoint {Point} Top-left point the target image data will be paste at. + */ + function (sourceTexture, sourceRect, destPoint) { + // Swap for drawImage if the sourceRect is the same size as the sourceTexture to avoid a costly getImageData call + if(sourceRect.equals(this.bounds) == true) { + this.context.drawImage(sourceTexture.canvas, destPoint.x, destPoint.y); + } else { + this.context.putImageData(sourceTexture.getPixels(sourceRect), destPoint.x, destPoint.y); + } + }; + DynamicTexture.prototype.assignCanvasToGameObjects = /** + * Given an array of GameObjects it will update each of them so that their canvas/contexts reference this DynamicTexture + * @param objects {Array} An array of GameObjects, or objects that inherit from it such as Sprites + */ + function (objects) { + for(var i = 0; i < objects.length; i++) { + objects[i].canvas = this.canvas; + objects[i].context = this.context; + } + }; + DynamicTexture.prototype.clear = /** + * Clear the whole canvas. + */ + function () { + this.context.clearRect(0, 0, this.bounds.width, this.bounds.height); + }; + DynamicTexture.prototype.render = /** + * Renders this DynamicTexture to the Stage at the given x/y coordinates + * + * @param x {number} The X coordinate to render on the stage to (given in screen coordinates, not world) + * @param y {number} The Y coordinate to render on the stage to (given in screen coordinates, not world) + */ + function (x, y) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + this._game.stage.context.drawImage(this.canvas, x, y); + }; + Object.defineProperty(DynamicTexture.prototype, "width", { + get: function () { + return this.bounds.width; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(DynamicTexture.prototype, "height", { + get: function () { + return this.bounds.height; + }, + enumerable: true, + configurable: true + }); + DynamicTexture.prototype.getColor32 = /** + * Given an alpha and 3 color values this will return an integer representation of it + * + * @param alpha {number} The Alpha value (between 0 and 255) + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xAARRGGBB) + */ + function (alpha, red, green, blue) { + return alpha << 24 | red << 16 | green << 8 | blue; + }; + DynamicTexture.prototype.getColor = /** + * Given 3 color values this will return an integer representation of it + * + * @param red {number} The Red channel value (between 0 and 255) + * @param green {number} The Green channel value (between 0 and 255) + * @param blue {number} The Blue channel value (between 0 and 255) + * + * @return A native color value integer (format: 0xRRGGBB) + */ + function (red, green, blue) { + return red << 16 | green << 8 | blue; + }; + return DynamicTexture; + })(); + Phaser.DynamicTexture = DynamicTexture; +})(Phaser || (Phaser = {})); diff --git a/Phaser/FXManager.js b/Phaser/FXManager.js new file mode 100644 index 00000000..1e9da3e2 --- /dev/null +++ b/Phaser/FXManager.js @@ -0,0 +1,150 @@ +/// +/** +* Phaser - FXManager +* +* The FXManager controls all special effects applied to game objects such as Cameras. +*/ +var Phaser; +(function (Phaser) { + var FXManager = (function () { + function FXManager(game, parent) { + this._game = game; + this._parent = parent; + this._fx = []; + this.active = true; + this.visible = true; + } + FXManager.prototype.add = /** + * Adds a new FX to the FXManager. + * The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender. + * A new instance of the effect will be created and a reference to Game will be passed to the object constructor. + * @param {object} effect + * @return {any} + */ + function (effect) { + var result = false; + var newEffect = { + effect: { + }, + preUpdate: false, + postUpdate: false, + preRender: false, + render: false, + postRender: false + }; + if(typeof effect === 'function') { + newEffect.effect = new effect(this._game, this._parent); + } else { + throw new Error("Invalid object given to Phaser.FXManager.add"); + } + // Check for methods now to avoid having to do this every loop + if(typeof newEffect.effect['preUpdate'] === 'function') { + newEffect.preUpdate = true; + result = true; + } + if(typeof newEffect.effect['postUpdate'] === 'function') { + newEffect.postUpdate = true; + result = true; + } + if(typeof newEffect.effect['preRender'] === 'function') { + newEffect.preRender = true; + result = true; + } + if(typeof newEffect.effect['render'] === 'function') { + newEffect.render = true; + result = true; + } + if(typeof newEffect.effect['postRender'] === 'function') { + newEffect.postRender = true; + result = true; + } + if(result == true) { + this._length = this._fx.push(newEffect); + return newEffect.effect; + } else { + return result; + } + }; + FXManager.prototype.preUpdate = /** + * Pre-update is called at the start of the objects update cycle, before any other updates have taken place. + */ + function () { + if(this.active) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preUpdate) { + this._fx[i].effect.preUpdate(); + } + } + } + }; + FXManager.prototype.postUpdate = /** + * Post-update is called at the end of the objects update cycle, after other update logic has taken place. + */ + function () { + if(this.active) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].postUpdate) { + this._fx[i].effect.postUpdate(); + } + } + } + }; + FXManager.prototype.preRender = /** + * Pre-render is called at the start of the object render cycle, before any transforms have taken place. + * It happens directly AFTER a canvas context.save has happened if added to a Camera. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preRender) { + this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + FXManager.prototype.render = /** + * render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered. + * @param {Camera} camera + * @param {number} cameraX + * @param {number} cameraY + * @param {number} cameraWidth + * @param {number} cameraHeight + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].preRender) { + this._fx[i].effect.preRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + FXManager.prototype.postRender = /** + * Post-render is called during the objects render cycle, after the children/image data has been rendered. + * It happens directly BEFORE a canvas context.restore has happened if added to a Camera. + */ + function (camera, cameraX, cameraY, cameraWidth, cameraHeight) { + if(this.visible) { + for(var i = 0; i < this._length; i++) { + if(this._fx[i].postRender) { + this._fx[i].effect.postRender(camera, cameraX, cameraY, cameraWidth, cameraHeight); + } + } + } + }; + FXManager.prototype.destroy = /** + * Clear down this FXManager and null out references + */ + function () { + this._game = null; + this._fx = null; + }; + return FXManager; + })(); + Phaser.FXManager = FXManager; +})(Phaser || (Phaser = {})); diff --git a/Phaser/GameMath.js b/Phaser/GameMath.js new file mode 100644 index 00000000..174f8ff6 --- /dev/null +++ b/Phaser/GameMath.js @@ -0,0 +1,922 @@ +/// +/** +* Phaser - GameMath +* +* Adds a set of extra Math functions used through-out Phaser. +* Includes methods written by Dylan Engelman and Adam Saltsman. +*/ +var Phaser; +(function (Phaser) { + var GameMath = (function () { + function GameMath(game) { + //arbitrary 8 digit epsilon + this.cosTable = []; + this.sinTable = []; + /** + * The global random number generator seed (for deterministic behavior in recordings and saves). + */ + this.globalSeed = Math.random(); + this._game = game; + } + GameMath.PI = 3.141592653589793; + GameMath.PI_2 = 1.5707963267948965; + GameMath.PI_4 = 0.7853981633974483; + GameMath.PI_8 = 0.39269908169872413; + GameMath.PI_16 = 0.19634954084936206; + GameMath.TWO_PI = 6.283185307179586; + GameMath.THREE_PI_2 = 4.7123889803846895; + GameMath.E = 2.71828182845905; + GameMath.LN10 = 2.302585092994046; + GameMath.LN2 = 0.6931471805599453; + GameMath.LOG10E = 0.4342944819032518; + GameMath.LOG2E = 1.442695040888963387; + GameMath.SQRT1_2 = 0.7071067811865476; + GameMath.SQRT2 = 1.4142135623730951; + GameMath.DEG_TO_RAD = 0.017453292519943294444444444444444; + GameMath.RAD_TO_DEG = 57.295779513082325225835265587527; + GameMath.B_16 = 65536; + GameMath.B_31 = 2147483648; + GameMath.B_32 = 4294967296; + GameMath.B_48 = 281474976710656; + GameMath.B_53 = 9007199254740992; + GameMath.B_64 = 18446744073709551616; + GameMath.ONE_THIRD = 0.333333333333333333333333333333333; + GameMath.TWO_THIRDS = 0.666666666666666666666666666666666; + GameMath.ONE_SIXTH = 0.166666666666666666666666666666666; + GameMath.COS_PI_3 = 0.86602540378443864676372317075294; + GameMath.SIN_2PI_3 = 0.03654595; + GameMath.CIRCLE_ALPHA = 0.5522847498307933984022516322796; + GameMath.ON = true; + GameMath.OFF = false; + GameMath.SHORT_EPSILON = 0.1; + GameMath.PERC_EPSILON = 0.001; + GameMath.EPSILON = 0.0001; + GameMath.LONG_EPSILON = 0.00000001; + GameMath.prototype.fuzzyEqual = function (a, b, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return Math.abs(a - b) < epsilon; + }; + GameMath.prototype.fuzzyLessThan = function (a, b, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return a < b + epsilon; + }; + GameMath.prototype.fuzzyGreaterThan = function (a, b, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return a > b - epsilon; + }; + GameMath.prototype.fuzzyCeil = function (val, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return Math.ceil(val - epsilon); + }; + GameMath.prototype.fuzzyFloor = function (val, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return Math.floor(val + epsilon); + }; + GameMath.prototype.average = function () { + var args = []; + for (var _i = 0; _i < (arguments.length - 0); _i++) { + args[_i] = arguments[_i + 0]; + } + var avg = 0; + for(var i = 0; i < args.length; i++) { + avg += args[i]; + } + return avg / args.length; + }; + GameMath.prototype.slam = function (value, target, epsilon) { + if (typeof epsilon === "undefined") { epsilon = 0.0001; } + return (Math.abs(value - target) < epsilon) ? target : value; + }; + GameMath.prototype.percentageMinMax = /** + * ratio of value to a range + */ + function (val, max, min) { + if (typeof min === "undefined") { min = 0; } + val -= min; + max -= min; + if(!max) { + return 0; + } else { + return val / max; + } + }; + GameMath.prototype.sign = /** + * a value representing the sign of the value. + * -1 for negative, +1 for positive, 0 if value is 0 + */ + function (n) { + if(n) { + return n / Math.abs(n); + } else { + return 0; + } + }; + GameMath.prototype.truncate = function (n) { + return (n > 0) ? Math.floor(n) : Math.ceil(n); + }; + GameMath.prototype.shear = function (n) { + return n % 1; + }; + GameMath.prototype.wrap = /** + * wrap a value around a range, similar to modulus with a floating minimum + */ + function (val, max, min) { + if (typeof min === "undefined") { min = 0; } + val -= min; + max -= min; + if(max == 0) { + return min; + } + val %= max; + val += min; + while(val < min) { + val += max; + } + return val; + }; + GameMath.prototype.arithWrap = /** + * arithmetic version of wrap... need to decide which is more efficient + */ + function (value, max, min) { + if (typeof min === "undefined") { min = 0; } + max -= min; + if(max == 0) { + return min; + } + return value - max * Math.floor((value - min) / max); + }; + GameMath.prototype.clamp = /** + * force a value within the boundaries of two values + * + * if max < min, min is returned + */ + function (input, max, min) { + if (typeof min === "undefined") { min = 0; } + return Math.max(min, Math.min(max, input)); + }; + GameMath.prototype.snapTo = /** + * Snap a value to nearest grid slice, using rounding. + * + * example if you have an interval gap of 5 and a position of 12... you will snap to 10. Where as 14 will snap to 15 + * + * @param input - the value to snap + * @param gap - the interval gap of the grid + * @param [start] - optional starting offset for gap + */ + function (input, gap, start) { + if (typeof start === "undefined") { start = 0; } + if(gap == 0) { + return input; + } + input -= start; + input = gap * Math.round(input / gap); + return start + input; + }; + GameMath.prototype.snapToFloor = /** + * Snap a value to nearest grid slice, using floor. + * + * example if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15 + * + * @param input - the value to snap + * @param gap - the interval gap of the grid + * @param [start] - optional starting offset for gap + */ + function (input, gap, start) { + if (typeof start === "undefined") { start = 0; } + if(gap == 0) { + return input; + } + input -= start; + input = gap * Math.floor(input / gap); + return start + input; + }; + GameMath.prototype.snapToCeil = /** + * Snap a value to nearest grid slice, using ceil. + * + * example if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20 + * + * @param input - the value to snap + * @param gap - the interval gap of the grid + * @param [start] - optional starting offset for gap + */ + function (input, gap, start) { + if (typeof start === "undefined") { start = 0; } + if(gap == 0) { + return input; + } + input -= start; + input = gap * Math.ceil(input / gap); + return start + input; + }; + GameMath.prototype.snapToInArray = /** + * Snaps a value to the nearest value in an array. + */ + function (input, arr, sort) { + if (typeof sort === "undefined") { sort = true; } + if(sort) { + arr.sort(); + } + if(input < arr[0]) { + return arr[0]; + } + var i = 1; + while(arr[i] < input) { + i++; + } + var low = arr[i - 1]; + var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; + return ((high - input) <= (input - low)) ? high : low; + }; + GameMath.prototype.roundTo = /** + * roundTo some place comparative to a 'base', default is 10 for decimal place + * + * 'place' is represented by the power applied to 'base' to get that place + * + * @param value - the value to round + * @param place - the place to round to + * @param base - the base to round in... default is 10 for decimal + * + * e.g. + * + * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 + * + * roundTo(2000/7,3) == 0 + * roundTo(2000/7,2) == 300 + * roundTo(2000/7,1) == 290 + * roundTo(2000/7,0) == 286 + * roundTo(2000/7,-1) == 285.7 + * roundTo(2000/7,-2) == 285.71 + * roundTo(2000/7,-3) == 285.714 + * roundTo(2000/7,-4) == 285.7143 + * roundTo(2000/7,-5) == 285.71429 + * + * roundTo(2000/7,3,2) == 288 -- 100100000 + * roundTo(2000/7,2,2) == 284 -- 100011100 + * roundTo(2000/7,1,2) == 286 -- 100011110 + * roundTo(2000/7,0,2) == 286 -- 100011110 + * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 + * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 + * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 + * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 + * + * note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed + * because we are rounding 100011.1011011011011011 which rounds up. + */ + function (value, place, base) { + if (typeof place === "undefined") { place = 0; } + if (typeof base === "undefined") { base = 10; } + var p = Math.pow(base, -place); + return Math.round(value * p) / p; + }; + GameMath.prototype.floorTo = function (value, place, base) { + if (typeof place === "undefined") { place = 0; } + if (typeof base === "undefined") { base = 10; } + var p = Math.pow(base, -place); + return Math.floor(value * p) / p; + }; + GameMath.prototype.ceilTo = function (value, place, base) { + if (typeof place === "undefined") { place = 0; } + if (typeof base === "undefined") { base = 10; } + var p = Math.pow(base, -place); + return Math.ceil(value * p) / p; + }; + GameMath.prototype.interpolateFloat = /** + * a one dimensional linear interpolation of a value. + */ + function (a, b, weight) { + return (b - a) * weight + a; + }; + GameMath.prototype.radiansToDegrees = /** + * convert radians to degrees + */ + function (angle) { + return angle * Phaser.GameMath.RAD_TO_DEG; + }; + GameMath.prototype.degreesToRadians = /** + * convert degrees to radians + */ + function (angle) { + return angle * Phaser.GameMath.DEG_TO_RAD; + }; + GameMath.prototype.angleBetween = /** + * Find the angle of a segment from (x1, y1) -> (x2, y2 ) + */ + function (x1, y1, x2, y2) { + return Math.atan2(y2 - y1, x2 - x1); + }; + GameMath.prototype.normalizeAngle = /** + * set an angle with in the bounds of -PI to PI + */ + function (angle, radians) { + if (typeof radians === "undefined") { radians = true; } + var rd = (radians) ? Phaser.GameMath.PI : 180; + return this.wrap(angle, rd, -rd); + }; + GameMath.prototype.nearestAngleBetween = /** + * closest angle between two angles from a1 to a2 + * absolute value the return for exact angle + */ + function (a1, a2, radians) { + if (typeof radians === "undefined") { radians = true; } + var rd = (radians) ? Phaser.GameMath.PI : 180; + a1 = this.normalizeAngle(a1, radians); + a2 = this.normalizeAngle(a2, radians); + if(a1 < -rd / 2 && a2 > rd / 2) { + a1 += rd * 2; + } + if(a2 < -rd / 2 && a1 > rd / 2) { + a2 += rd * 2; + } + return a2 - a1; + }; + GameMath.prototype.normalizeAngleToAnother = /** + * normalizes independent and then sets dep to the nearest value respective to independent + * + * for instance if dep=-170 and ind=170 then 190 will be returned as an alternative to -170 + */ + function (dep, ind, radians) { + if (typeof radians === "undefined") { radians = true; } + return ind + this.nearestAngleBetween(ind, dep, radians); + }; + GameMath.prototype.normalizeAngleAfterAnother = /** + * normalize independent and dependent and then set dependent to an angle relative to 'after/clockwise' independent + * + * for instance dep=-170 and ind=170, then 190 will be reutrned as alternative to -170 + */ + function (dep, ind, radians) { + if (typeof radians === "undefined") { radians = true; } + dep = this.normalizeAngle(dep - ind, radians); + return ind + dep; + }; + GameMath.prototype.normalizeAngleBeforeAnother = /** + * normalizes indendent and dependent and then sets dependent to an angle relative to 'before/counterclockwise' independent + * + * for instance dep = 190 and ind = 170, then -170 will be returned as an alternative to 190 + */ + function (dep, ind, radians) { + if (typeof radians === "undefined") { radians = true; } + dep = this.normalizeAngle(ind - dep, radians); + return ind - dep; + }; + GameMath.prototype.interpolateAngles = /** + * interpolate across the shortest arc between two angles + */ + function (a1, a2, weight, radians, ease) { + if (typeof radians === "undefined") { radians = true; } + if (typeof ease === "undefined") { ease = null; } + a1 = this.normalizeAngle(a1, radians); + a2 = this.normalizeAngleToAnother(a2, a1, radians); + return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight); + }; + GameMath.prototype.logBaseOf = /** + * Compute the logarithm of any value of any base + * + * a logarithm is the exponent that some constant (base) would have to be raised to + * to be equal to value. + * + * i.e. + * 4 ^ x = 16 + * can be rewritten as to solve for x + * logB4(16) = x + * which with this function would be + * LoDMath.logBaseOf(16,4) + * + * which would return 2, because 4^2 = 16 + */ + function (value, base) { + return Math.log(value) / Math.log(base); + }; + GameMath.prototype.GCD = /** + * Greatest Common Denominator using Euclid's algorithm + */ + function (m, n) { + var r; + //make sure positive, GCD is always positive + m = Math.abs(m); + n = Math.abs(n); + //m must be >= n + if(m < n) { + r = m; + m = n; + n = r; + } + //now start loop + while(true) { + r = m % n; + if(!r) { + return n; + } + m = n; + n = r; + } + return 1; + }; + GameMath.prototype.LCM = /** + * Lowest Common Multiple + */ + function (m, n) { + return (m * n) / this.GCD(m, n); + }; + GameMath.prototype.factorial = /** + * Factorial - N! + * + * simple product series + * + * by definition: + * 0! == 1 + */ + function (value) { + if(value == 0) { + return 1; + } + var res = value; + while(--value) { + res *= value; + } + return res; + }; + GameMath.prototype.gammaFunction = /** + * gamma function + * + * defined: gamma(N) == (N - 1)! + */ + function (value) { + return this.factorial(value - 1); + }; + GameMath.prototype.fallingFactorial = /** + * falling factorial + * + * defined: (N)! / (N - x)! + * + * written subscript: (N)x OR (base)exp + */ + function (base, exp) { + return this.factorial(base) / this.factorial(base - exp); + }; + GameMath.prototype.risingFactorial = /** + * rising factorial + * + * defined: (N + x - 1)! / (N - 1)! + * + * written superscript N^(x) OR base^(exp) + */ + function (base, exp) { + //expanded from gammaFunction for speed + return this.factorial(base + exp - 1) / this.factorial(base - 1); + }; + GameMath.prototype.binCoef = /** + * binomial coefficient + * + * defined: N! / (k!(N-k)!) + * reduced: N! / (N-k)! == (N)k (fallingfactorial) + * reduced: (N)k / k! + */ + function (n, k) { + return this.fallingFactorial(n, k) / this.factorial(k); + }; + GameMath.prototype.risingBinCoef = /** + * rising binomial coefficient + * + * as one can notice in the analysis of binCoef(...) that + * binCoef is the (N)k divided by k!. Similarly rising binCoef + * is merely N^(k) / k! + */ + function (n, k) { + return this.risingFactorial(n, k) / this.factorial(k); + }; + GameMath.prototype.chanceRoll = /** + * Generate a random boolean result based on the chance value + *

+ * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance + * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. + *

+ * @param chance The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%) + * @return true if the roll passed, or false + */ + function (chance) { + if (typeof chance === "undefined") { chance = 50; } + if(chance <= 0) { + return false; + } else if(chance >= 100) { + return true; + } else { + if(Math.random() * 100 >= chance) { + return false; + } else { + return true; + } + } + }; + GameMath.prototype.maxAdd = /** + * Adds the given amount to the value, but never lets the value go over the specified maximum + * + * @param value The value to add the amount to + * @param amount The amount to add to the value + * @param max The maximum the value is allowed to be + * @return The new value + */ + function (value, amount, max) { + value += amount; + if(value > max) { + value = max; + } + return value; + }; + GameMath.prototype.minSub = /** + * Subtracts the given amount from the value, but never lets the value go below the specified minimum + * + * @param value The base value + * @param amount The amount to subtract from the base value + * @param min The minimum the value is allowed to be + * @return The new value + */ + function (value, amount, min) { + value -= amount; + if(value < min) { + value = min; + } + return value; + }; + GameMath.prototype.wrapValue = /** + * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. + *

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

+ * + * @param value The value to add the amount to + * @param amount The amount to add to the value + * @param max The maximum the value is allowed to be + * @return The wrapped value + */ + function (value, amount, max) { + var diff; + value = Math.abs(value); + amount = Math.abs(amount); + max = Math.abs(max); + diff = (value + amount) % max; + return diff; + }; + GameMath.prototype.randomSign = /** + * Randomly returns either a 1 or -1 + * + * @return 1 or -1 + */ + function () { + return (Math.random() > 0.5) ? 1 : -1; + }; + GameMath.prototype.isOdd = /** + * Returns true if the number given is odd. + * + * @param n The number to check + * + * @return True if the given number is odd. False if the given number is even. + */ + function (n) { + if(n & 1) { + return true; + } else { + return false; + } + }; + GameMath.prototype.isEven = /** + * Returns true if the number given is even. + * + * @param n The number to check + * + * @return True if the given number is even. False if the given number is odd. + */ + function (n) { + if(n & 1) { + return false; + } else { + return true; + } + }; + GameMath.prototype.wrapAngle = /** + * Keeps an angle value between -180 and +180
+ * Should be called whenever the angle is updated on the Sprite to stop it from going insane. + * + * @param angle The angle value to check + * + * @return The new angle value, returns the same as the input angle if it was within bounds + */ + function (angle) { + var result = angle; + // Nothing needs to change + if(angle >= -180 && angle <= 180) { + return angle; + } + // Else normalise it to -180, 180 + result = (angle + 180) % 360; + if(result < 0) { + result += 360; + } + return result - 180; + }; + GameMath.prototype.angleLimit = /** + * Keeps an angle value between the given min and max values + * + * @param angle The angle value to check. Must be between -180 and +180 + * @param min The minimum angle that is allowed (must be -180 or greater) + * @param max The maximum angle that is allowed (must be 180 or less) + * + * @return The new angle value, returns the same as the input angle if it was within bounds + */ + function (angle, min, max) { + var result = angle; + if(angle > max) { + result = max; + } else if(angle < min) { + result = min; + } + return result; + }; + GameMath.prototype.linearInterpolation = /** + * @method linear + * @param {Any} v + * @param {Any} k + * @static + */ + function (v, k) { + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + if(k < 0) { + return this.linear(v[0], v[1], f); + } + if(k > 1) { + return this.linear(v[m], v[m - 1], m - f); + } + return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); + }; + GameMath.prototype.bezierInterpolation = /** + * @method Bezier + * @param {Any} v + * @param {Any} k + * @static + */ + function (v, k) { + var b = 0; + var n = v.length - 1; + for(var i = 0; i <= n; i++) { + b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i); + } + return b; + }; + GameMath.prototype.catmullRomInterpolation = /** + * @method CatmullRom + * @param {Any} v + * @param {Any} k + * @static + */ + function (v, k) { + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + if(v[0] === v[m]) { + if(k < 0) { + i = Math.floor(f = m * (1 + k)); + } + return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); + } else { + if(k < 0) { + return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]); + } + if(k > 1) { + return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); + } + return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + } + }; + GameMath.prototype.linear = /** + * @method Linear + * @param {Any} p0 + * @param {Any} p1 + * @param {Any} t + * @static + */ + function (p0, p1, t) { + return (p1 - p0) * t + p0; + }; + GameMath.prototype.bernstein = /** + * @method Bernstein + * @param {Any} n + * @param {Any} i + * @static + */ + function (n, i) { + return this.factorial(n) / this.factorial(i) / this.factorial(n - i); + }; + GameMath.prototype.catmullRom = /** + * @method CatmullRom + * @param {Any} p0 + * @param {Any} p1 + * @param {Any} p2 + * @param {Any} p3 + * @param {Any} t + * @static + */ + function (p0, p1, p2, p3, t) { + var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + }; + GameMath.prototype.difference = function (a, b) { + return Math.abs(a - b); + }; + GameMath.prototype.random = /** + * Generates a random number. Deterministic, meaning safe + * to use if you want to record replays in random environments. + * + * @return A Number between 0 and 1. + */ + function () { + return this.globalSeed = this.srand(this.globalSeed); + }; + GameMath.prototype.srand = /** + * Generates a random number based on the seed provided. + * + * @param Seed A number between 0 and 1, used to generate a predictable random number (very optional). + * + * @return A Number between 0 and 1. + */ + function (Seed) { + return ((69621 * (Seed * 0x7FFFFFFF)) % 0x7FFFFFFF) / 0x7FFFFFFF; + }; + GameMath.prototype.getRandom = /** + * Fetch a random entry from the given array. + * Will return null if random selection is missing, or array has no entries. + * + * @param objects An array of objects. + * @param startIndex Optional offset off the front of the array. Default value is 0, or the beginning of the array. + * @param length Optional restriction on the number of values you want to randomly select from. + * + * @return The random object that was selected. + */ + function (objects, startIndex, length) { + if (typeof startIndex === "undefined") { startIndex = 0; } + if (typeof length === "undefined") { length = 0; } + if(objects != null) { + var l = length; + if((l == 0) || (l > objects.length - startIndex)) { + l = objects.length - startIndex; + } + if(l > 0) { + return objects[startIndex + Math.floor(Math.random() * l)]; + } + } + return null; + }; + GameMath.prototype.floor = /** + * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2. + * + * @param Value Any number. + * + * @return The rounded value of that number. + */ + function (Value) { + var n = Value | 0; + return (Value > 0) ? (n) : ((n != Value) ? (n - 1) : (n)); + }; + GameMath.prototype.ceil = /** + * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3. + * + * @param Value Any number. + * + * @return The rounded value of that number. + */ + function (Value) { + var n = Value | 0; + return (Value > 0) ? ((n != Value) ? (n + 1) : (n)) : (n); + }; + GameMath.prototype.sinCosGenerator = /** + * Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at + *

+ * The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function + * you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time. + *

+ * @param length The length of the wave + * @param sinAmplitude The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param cosAmplitude The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value + * @param frequency The frequency of the sine and cosine table data + * @return Returns the sine table + * @see getSinTable + * @see getCosTable + */ + function (length, sinAmplitude, cosAmplitude, frequency) { + if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; } + if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; } + if (typeof frequency === "undefined") { frequency = 1.0; } + var sin = sinAmplitude; + var cos = cosAmplitude; + var frq = frequency * Math.PI / length; + this.cosTable = []; + this.sinTable = []; + for(var c = 0; c < length; c++) { + cos -= sin * frq; + sin += cos * frq; + this.cosTable[c] = cos; + this.sinTable[c] = sin; + } + return this.sinTable; + }; + GameMath.prototype.shiftSinTable = /** + * Shifts through the sin table data by one value and returns it. + * This effectively moves the position of the data from the start to the end of the table. + * @return The sin value. + */ + function () { + if(this.sinTable) { + var s = this.sinTable.shift(); + this.sinTable.push(s); + return s; + } + }; + GameMath.prototype.shiftCosTable = /** + * Shifts through the cos table data by one value and returns it. + * This effectively moves the position of the data from the start to the end of the table. + * @return The cos value. + */ + function () { + if(this.cosTable) { + var s = this.cosTable.shift(); + this.cosTable.push(s); + 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 + * @return The array + */ + function (array) { + for(var i = array.length - 1; i > 0; i--) { + var j = Math.floor(Math.random() * (i + 1)); + var temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + return array; + }; + GameMath.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) { + var dx = x1 - x2; + var dy = y1 - y2; + 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 + * @param x {number} The x coordinate of the anchor point + * @param y {number} The y coordinate of the anchor point + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Number} distance An optional distance constraint between the point and the anchor + * @return The modified point object + */ + function (point, x1, y1, angle, asDegrees, distance) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + if (typeof distance === "undefined") { distance = null; } + if(asDegrees) { + angle = angle * Phaser.GameMath.DEG_TO_RAD; + } + // Get distance from origin to the point + if(distance === null) { + distance = Math.sqrt(((x1 - point.x) * (x1 - point.x)) + ((y1 - point.y) * (y1 - point.y))); + } + point.x = x1 + distance * Math.cos(angle); + point.y = y1 + distance * Math.sin(angle); + return point; + }; + return GameMath; + })(); + Phaser.GameMath = GameMath; +})(Phaser || (Phaser = {})); diff --git a/Phaser/GameObjectFactory.js b/Phaser/GameObjectFactory.js new file mode 100644 index 00000000..6f6f8f7b --- /dev/null +++ b/Phaser/GameObjectFactory.js @@ -0,0 +1,200 @@ +/// +/** +* Phaser - GameObjectFactory +* +* A quick way to create new world objects and add existing objects to the current world. +*/ +var Phaser; +(function (Phaser) { + var GameObjectFactory = (function () { + /** + * GameObjectFactory constructor + * @param game {Game} A reference to the current Game. + */ + function GameObjectFactory(game) { + this._game = game; + this._world = this._game.world; + } + GameObjectFactory.prototype.camera = /** + * Create a new camera with specific position and size. + * + * @param x {number} X position of the new camera. + * @param y {number} Y position of the new camera. + * @param width {number} Width of the new camera. + * @param height {number} Height of the new camera. + * @returns {Camera} The newly created camera object. + */ + function (x, y, width, height) { + return this._world.createCamera(x, y, width, height); + }; + GameObjectFactory.prototype.geomSprite = /** + * Create a new GeomSprite with specific position. + * + * @param x {number} X position of the new geom sprite. + * @param y {number} Y position of the new geom sprite. + * @returns {GeomSprite} The newly created geom sprite object. + */ + function (x, y) { + return this._world.createGeomSprite(x, y); + }; + GameObjectFactory.prototype.sprite = /** + * 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. + */ + function (x, y, key) { + if (typeof key === "undefined") { key = ''; } + return this._world.createSprite(x, y, key); + }; + GameObjectFactory.prototype.dynamicTexture = /** + * Create a new DynamicTexture with specific size. + * + * @param width {number} Width of the texture. + * @param height {number} Height of the texture. + * @returns {DynamicTexture} The newly created dynamic texture object. + */ + function (width, height) { + return this._world.createDynamicTexture(width, height); + }; + GameObjectFactory.prototype.group = /** + * Create a new object container. + * + * @param maxSize {number} Optional, capacity of this group. + * @returns {Group} The newly created group. + */ + function (maxSize) { + if (typeof maxSize === "undefined") { maxSize = 0; } + return this._world.createGroup(maxSize); + }; + GameObjectFactory.prototype.particle = /** + * Create a new Particle. + * + * @return {Particle} The newly created particle object. + */ + function () { + return this._world.createParticle(); + }; + GameObjectFactory.prototype.emitter = /** + * 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. + */ + function (x, y, size) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof size === "undefined") { size = 0; } + return this._world.createEmitter(x, y, size); + }; + GameObjectFactory.prototype.scrollZone = /** + * Create a new ScrollZone object with image key, position and size. + * + * @param key {string} Key to a image you wish this object to use. + * @param x {number} X position of this object. + * @param y {number} Y position of this object. + * @param width number} Width of this object. + * @param height {number} Height of this object. + * @returns {ScrollZone} The newly created scroll zone object. + */ + function (key, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + return this._world.createScrollZone(key, x, y, width, height); + }; + GameObjectFactory.prototype.tilemap = /** + * Create a new Tilemap. + * + * @param key {string} Key for tileset image. + * @param mapData {string} Data of this tilemap. + * @param format {number} Format of map data. (Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON) + * @param [resizeWorld] {boolean} resize the world to make same as tilemap? + * @param [tileWidth] {number} width of each tile. + * @param [tileHeight] {number} height of each tile. + * @return {Tilemap} The newly created tilemap object. + */ + function (key, mapData, format, resizeWorld, tileWidth, tileHeight) { + if (typeof resizeWorld === "undefined") { resizeWorld = true; } + if (typeof tileWidth === "undefined") { tileWidth = 0; } + if (typeof tileHeight === "undefined") { tileHeight = 0; } + return this._world.createTilemap(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. + * @return {Phaser.Tween} The newly created tween object. + */ + function (obj) { + return this._game.tweens.create(obj); + }; + GameObjectFactory.prototype.existingSprite = /** + * Add an existing Sprite to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param sprite The Sprite to add to the Game World + * @return {Phaser.Sprite} The Sprite object + */ + function (sprite) { + return this._world.group.add(sprite); + }; + GameObjectFactory.prototype.existingGeomSprite = /** + * Add an existing GeomSprite to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param sprite The GeomSprite to add to the Game World + * @return {Phaser.GeomSprite} The GeomSprite object + */ + function (sprite) { + return this._world.group.add(sprite); + }; + GameObjectFactory.prototype.existingEmitter = /** + * Add an existing Emitter to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param emitter The Emitter to add to the Game World + * @return {Phaser.Emitter} The Emitter object + */ + function (emitter) { + return this._world.group.add(emitter); + }; + GameObjectFactory.prototype.existingScrollZone = /** + * Add an existing ScrollZone to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param scrollZone The ScrollZone to add to the Game World + * @return {Phaser.ScrollZone} The ScrollZone object + */ + function (scrollZone) { + return this._world.group.add(scrollZone); + }; + GameObjectFactory.prototype.existingTilemap = /** + * Add an existing Tilemap to the current world. + * Note: This doesn't check or update the objects reference to Game. If that is wrong, all kinds of things will break. + * + * @param tilemap The Tilemap to add to the Game World + * @return {Phaser.Tilemap} The Tilemap object + */ + function (tilemap) { + return this._world.group.add(tilemap); + }; + GameObjectFactory.prototype.existingTween = /** + * 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. + * + * @param tween The Tween to add to the Game World + * @return {Phaser.Tween} The Tween object + */ + function (tween) { + return this._game.tweens.add(tween); + }; + return GameObjectFactory; + })(); + Phaser.GameObjectFactory = GameObjectFactory; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Group.js b/Phaser/Group.js new file mode 100644 index 00000000..84e9b207 --- /dev/null +++ b/Phaser/Group.js @@ -0,0 +1,598 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/** +* Phaser - Group +* +* This class is used for organising, updating and sorting game objects. +*/ +var Phaser; +(function (Phaser) { + var Group = (function (_super) { + __extends(Group, _super); + function Group(game, MaxSize) { + if (typeof MaxSize === "undefined") { MaxSize = 0; } + _super.call(this, game); + /** + * 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.isGroup = 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.hideFromCamera = /** + * If you do not wish this object to be visible to a specific camera, pass the camera here. + * + * @param camera {Camera} The specific camera. + */ + function (camera) { + if(this.cameraBlacklist.indexOf(camera.ID) == -1) { + this.cameraBlacklist.push(camera.ID); + } + }; + Group.prototype.showToCamera = /** + * Make this object only visible to a specific camera. + * + * @param camera {Camera} The camera you wish it to be visible. + */ + function (camera) { + if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { + this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); + } + }; + Group.prototype.clearCameraList = /** + * This clears the camera black list, making the GameObject visible to all cameras. + */ + function () { + this.cameraBlacklist.length = 0; + }; + Group.prototype.destroy = /** + * Override this function to handle any deleting or "shutdown" type operations you might need, + * such as removing traditional Flash children like Basic objects. + */ + function () { + if(this.members != null) { + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null) { + basic.destroy(); + } + } + this.members.length = 0; + } + this._sortIndex = null; + }; + Group.prototype.update = /** + * Automatically goes through and calls update on everything you added. + */ + function (forceUpdate) { + if (typeof forceUpdate === "undefined") { forceUpdate = false; } + if(this.ignoreGlobalUpdate && forceUpdate == false) { + return; + } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && basic.exists && basic.active && basic.ignoreGlobalUpdate == false) { + basic.preUpdate(); + basic.update(forceUpdate); + basic.postUpdate(); + } + } + }; + Group.prototype.render = /** + * Automatically goes through and calls render on everything you added. + */ + function (camera, cameraOffsetX, cameraOffsetY, forceRender) { + if (typeof forceRender === "undefined") { forceRender = false; } + if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { + return; + } + if(this.ignoreGlobalRender && forceRender == false) { + return; + } + if(this.globalCompositeOperation) { + this._game.stage.context.save(); + this._game.stage.context.globalCompositeOperation = this.globalCompositeOperation; + } + if(this.alpha > 0) { + var prevAlpha = this._game.stage.context.globalAlpha; + this._game.stage.context.globalAlpha = this.alpha; + } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && basic.exists && basic.visible && basic.ignoreGlobalRender == false) { + basic.render(camera, cameraOffsetX, cameraOffsetY, forceRender); + } + } + if(this.alpha > 0) { + this._game.stage.context.globalAlpha = 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 + var basic; + var i = this._maxSize; + var l = this.members.length; + while(i < l) { + basic = this.members[i++]; + if(basic != null) { + basic.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. + var i = 0; + var l = this.members.length; + while(i < l) { + if(this.members[i] == null) { + this.members[i] = Object; + if(i >= this.length) { + this.length = i + 1; + } + return Object; + } + 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[i] = Object; + this.length = 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; } + var basic; + if(this._maxSize > 0) { + if(this.length < this._maxSize) { + if(ObjectClass == null) { + return null; + } + return this.add(new ObjectClass(this._game)); + } else { + basic = this.members[this._marker++]; + if(this._marker >= this._maxSize) { + this._marker = 0; + } + return basic; + } + } else { + basic = this.getFirstAvailable(ObjectClass); + if(basic != null) { + return basic; + } + 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; } + var index = this.members.indexOf(object); + if((index < 0) || (index >= this.members.length)) { + return null; + } + if(splice) { + this.members.splice(index, 1); + this.length--; + } else { + this.members[index] = 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) { + var index = this.members.indexOf(oldObject); + if((index < 0) || (index >= this.members.length)) { + return null; + } + this.members[index] = 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 = Phaser.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; } + var basic; + var i = 0; + while(i < length) { + basic = this.members[i++]; + if(basic != null) { + if(Recurse && (basic.isGroup == true)) { + basic['setAll'](VariableName, Value, Recurse); + } else { + basic[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; } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null) { + if(Recurse && (basic.isGroup == true)) { + basic['callAll'](FunctionName, Recurse); + } else { + basic[FunctionName](); + } + } + } + }; + Group.prototype.forEach = /** + * @param {function} callback + * @param {boolean} recursive + */ + function (callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null) { + if(recursive && (basic.isGroup == true)) { + basic.forEach(callback, true); + } else { + callback.call(this, basic); + } + } + } + }; + Group.prototype.forEachAlive = /** + * @param {any} context + * @param {function} callback + * @param {boolean} recursive + */ + function (context, callback, recursive) { + if (typeof recursive === "undefined") { recursive = false; } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null && basic.alive) { + if(recursive && (basic.isGroup == true)) { + basic.forEachAlive(context, callback, true); + } else { + callback.call(context, basic); + } + } + } + }; + 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; } + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && !basic.exists && ((ObjectClass == null) || (typeof basic === ObjectClass))) { + return basic; + } + } + 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 () { + var basic; + var i = 0; + var l = this.members.length; + while(i < l) { + if(this.members[i] == null) { + return i; + } else { + 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 () { + var basic; + var i = 0; + while(i < length) { + basic = this.members[i++]; + if((basic != null) && basic.exists) { + return basic; + } + } + 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 () { + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && basic.exists && basic.alive) { + return basic; + } + } + 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 () { + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && !basic.alive) { + return basic; + } + } + 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 () { + var count = -1; + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null) { + if(count < 0) { + count = 0; + } + if(basic.exists && basic.alive) { + count++; + } + } + } + return 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 () { + var count = -1; + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if(basic != null) { + if(count < 0) { + count = 0; + } + if(!basic.alive) { + count++; + } + } + } + return 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 () { + var basic; + var i = 0; + while(i < this.length) { + basic = this.members[i++]; + if((basic != null) && basic.exists) { + basic.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.Basic); + Phaser.Group = Group; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Loader.js b/Phaser/Loader.js new file mode 100644 index 00000000..532e9bdc --- /dev/null +++ b/Phaser/Loader.js @@ -0,0 +1,309 @@ +/// +/** +* Phaser - Loader +* +* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. +* It uses a combination of Image() loading and xhr and provides for progress and completion callbacks. +*/ +var Phaser; +(function (Phaser) { + var Loader = (function () { + function Loader(game, callback) { + this._game = game; + this._gameCreateComplete = callback; + this._keys = []; + this._fileList = { + }; + this._xhr = new XMLHttpRequest(); + this._queueSize = 0; + } + Loader.prototype.reset = function () { + this._queueSize = 0; + }; + Object.defineProperty(Loader.prototype, "queueSize", { + get: function () { + return this._queueSize; + }, + enumerable: true, + configurable: true + }); + Loader.prototype.addImageFile = function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'image', + key: key, + url: url, + data: null, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.addSpriteSheet = function (key, url, frameWidth, frameHeight, frameMax) { + if (typeof frameMax === "undefined") { frameMax = -1; } + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'spritesheet', + key: key, + url: url, + data: null, + frameWidth: frameWidth, + frameHeight: frameHeight, + frameMax: frameMax, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.addTextureAtlas = function (key, url, jsonURL, jsonData) { + if (typeof jsonURL === "undefined") { jsonURL = null; } + if (typeof jsonData === "undefined") { jsonData = null; } + if(this.checkKeyExists(key) === false) { + if(jsonURL !== null) { + // A URL to a json file has been given + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: url, + data: null, + jsonURL: jsonURL, + jsonData: null, + error: false, + loaded: false + }; + this._keys.push(key); + } else { + // A json string or object has been given + if(typeof jsonData === 'string') { + var data = JSON.parse(jsonData); + // Malformed? + if(data['frames']) { + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: url, + data: null, + jsonURL: null, + jsonData: data['frames'], + error: false, + loaded: false + }; + this._keys.push(key); + } + } else { + // Malformed? + if(jsonData['frames']) { + this._queueSize++; + this._fileList[key] = { + type: 'textureatlas', + key: key, + url: url, + data: null, + jsonURL: null, + jsonData: jsonData['frames'], + error: false, + loaded: false + }; + this._keys.push(key); + } + } + } + } + }; + Loader.prototype.addAudioFile = function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'audio', + key: key, + url: url, + data: null, + buffer: null, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.addTextFile = function (key, url) { + if(this.checkKeyExists(key) === false) { + this._queueSize++; + this._fileList[key] = { + type: 'text', + key: key, + url: url, + data: null, + error: false, + loaded: false + }; + this._keys.push(key); + } + }; + Loader.prototype.removeFile = function (key) { + delete this._fileList[key]; + }; + Loader.prototype.removeAll = function () { + this._fileList = { + }; + }; + Loader.prototype.load = function (onFileLoadCallback, onCompleteCallback) { + if (typeof onFileLoadCallback === "undefined") { onFileLoadCallback = null; } + if (typeof onCompleteCallback === "undefined") { onCompleteCallback = null; } + this.progress = 0; + this.hasLoaded = false; + this._onComplete = onCompleteCallback; + if(onCompleteCallback == null) { + this._onComplete = this._game.onCreateCallback; + } + this._onFileLoad = onFileLoadCallback; + if(this._keys.length > 0) { + this._progressChunk = 100 / this._keys.length; + this.loadFile(); + } else { + this.progress = 1; + this.hasLoaded = true; + this._gameCreateComplete.call(this._game); + if(this._onComplete !== null) { + this._onComplete.call(this._game.callbackContext); + } + } + }; + Loader.prototype.loadFile = function () { + var _this = this; + var file = this._fileList[this._keys.pop()]; + // Image or Data? + switch(file.type) { + case 'image': + case 'spritesheet': + case 'textureatlas': + file.data = new Image(); + file.data.name = file.key; + file.data.onload = function () { + return _this.fileComplete(file.key); + }; + file.data.onerror = function () { + return _this.fileError(file.key); + }; + file.data.src = file.url; + break; + case 'audio': + this._xhr.open("GET", file.url, true); + this._xhr.responseType = "arraybuffer"; + this._xhr.onload = function () { + return _this.fileComplete(file.key); + }; + this._xhr.onerror = function () { + return _this.fileError(file.key); + }; + this._xhr.send(); + break; + case 'text': + this._xhr.open("GET", file.url, true); + this._xhr.responseType = "text"; + this._xhr.onload = function () { + return _this.fileComplete(file.key); + }; + this._xhr.onerror = function () { + return _this.fileError(file.key); + }; + this._xhr.send(); + break; + } + }; + Loader.prototype.fileError = function (key) { + this._fileList[key].loaded = true; + this._fileList[key].error = true; + this.nextFile(key, false); + }; + Loader.prototype.fileComplete = function (key) { + var _this = this; + this._fileList[key].loaded = true; + var file = this._fileList[key]; + var loadNext = true; + switch(file.type) { + case 'image': + this._game.cache.addImage(file.key, file.url, file.data); + break; + case 'spritesheet': + this._game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax); + break; + case 'textureatlas': + if(file.jsonURL == null) { + this._game.cache.addTextureAtlas(file.key, file.url, file.data, file.jsonData); + } else { + // Load the JSON before carrying on with the next file + loadNext = false; + this._xhr.open("GET", file.jsonURL, true); + this._xhr.responseType = "text"; + this._xhr.onload = function () { + return _this.jsonLoadComplete(file.key); + }; + this._xhr.onerror = function () { + return _this.jsonLoadError(file.key); + }; + this._xhr.send(); + } + break; + case 'audio': + file.data = this._xhr.response; + this._game.cache.addSound(file.key, file.url, file.data); + break; + case 'text': + file.data = this._xhr.response; + this._game.cache.addText(file.key, file.url, file.data); + break; + } + if(loadNext) { + this.nextFile(key, true); + } + }; + Loader.prototype.jsonLoadComplete = function (key) { + var data = JSON.parse(this._xhr.response); + // Malformed? + if(data['frames']) { + var file = this._fileList[key]; + this._game.cache.addTextureAtlas(file.key, file.url, file.data, data['frames']); + } + this.nextFile(key, true); + }; + Loader.prototype.jsonLoadError = function (key) { + var file = this._fileList[key]; + file.error = true; + this.nextFile(key, true); + }; + Loader.prototype.nextFile = function (previousKey, success) { + this.progress = Math.round(this.progress + this._progressChunk); + if(this.progress > 1) { + this.progress = 1; + } + if(this._onFileLoad) { + this._onFileLoad.call(this._game.callbackContext, this.progress, previousKey, success); + } + if(this._keys.length > 0) { + this.loadFile(); + } else { + this.hasLoaded = true; + this.removeAll(); + this._gameCreateComplete.call(this._game); + if(this._onComplete !== null) { + this._onComplete.call(this._game.callbackContext); + } + } + }; + Loader.prototype.checkKeyExists = function (key) { + if(this._fileList[key]) { + return true; + } else { + return false; + } + }; + return Loader; + })(); + Phaser.Loader = Loader; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Motion.js b/Phaser/Motion.js new file mode 100644 index 00000000..b9ca3974 --- /dev/null +++ b/Phaser/Motion.js @@ -0,0 +1,313 @@ +/// +/// +/** +* 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.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, Acceleration, Drag, Max) { + if (typeof Acceleration === "undefined") { Acceleration = 0; } + if (typeof Drag === "undefined") { Drag = 0; } + if (typeof Max === "undefined") { Max = 10000; } + if(Acceleration !== 0) { + Velocity += Acceleration * this._game.time.elapsed; + } else if(Drag !== 0) { + var drag = Drag * this._game.time.elapsed; + if(Velocity - drag > 0) { + Velocity = Velocity - drag; + } else if(Velocity + drag < 0) { + Velocity += drag; + } else { + Velocity = 0; + } + } + if((Velocity != 0) && (Max != 10000)) { + if(Velocity > Max) { + Velocity = Max; + } else if(Velocity < -Max) { + Velocity = -Max; + } + } + return Velocity; + }; + Motion.prototype.velocityFromAngle = /** + * Given the angle and speed calculate the velocity and return it as a Point + * + * @param {number} angle The angle (in degrees) calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} A Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + function (angle, speed) { + if(isNaN(speed)) { + speed = 0; + } + var a = this._game.math.degreesToRadians(angle); + return new Phaser.Point((Math.cos(a) * speed), (Math.sin(a) * speed)); + }; + Motion.prototype.moveTowardsObject = /** + * Sets the source Sprite x/y velocity so it will move directly towards the destination Sprite at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * If you need the object to accelerate, see accelerateTowardsObject() instead + * Note: Doesn't take into account acceleration, maxVelocity or drag (if you set drag or acceleration too high this object may not move at all) + * + * @param {GameObject} source The Sprite on which the velocity will be set + * @param {GameObject} dest The Sprite where the source object will move to + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + function (source, dest, speed, maxTime) { + if (typeof speed === "undefined") { speed = 60; } + if (typeof maxTime === "undefined") { maxTime = 0; } + var a = this.angleBetween(source, dest); + if(maxTime > 0) { + var d = this.distanceBetween(source, dest); + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } + source.velocity.x = Math.cos(a) * speed; + source.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsObject = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the destination Sprite at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsObject() instead. + * + * @param {GameObject} source The Sprite on which the acceleration will be set + * @param {GameObject} dest The Sprite where the source object will move towards + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + function (source, dest, speed, xSpeedMax, ySpeedMax) { + var a = this.angleBetween(source, dest); + source.velocity.x = 0; + source.velocity.y = 0; + source.acceleration.x = Math.cos(a) * speed; + source.acceleration.y = Math.sin(a) * speed; + source.maxVelocity.x = xSpeedMax; + source.maxVelocity.y = ySpeedMax; + }; + Motion.prototype.moveTowardsMouse = /** + * Move the given Sprite towards the mouse pointer coordinates at a steady velocity + * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * + * @param {GameObject} source The Sprite to move + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + function (source, speed, maxTime) { + if (typeof speed === "undefined") { speed = 60; } + if (typeof maxTime === "undefined") { maxTime = 0; } + var a = this.angleBetweenMouse(source); + if(maxTime > 0) { + var d = this.distanceToMouse(source); + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } + source.velocity.x = Math.cos(a) * speed; + source.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsMouse = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the mouse coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsMouse() instead. + * + * @param {GameObject} source The Sprite on which the acceleration will be set + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + function (source, speed, xSpeedMax, ySpeedMax) { + var a = this.angleBetweenMouse(source); + source.velocity.x = 0; + source.velocity.y = 0; + source.acceleration.x = Math.cos(a) * speed; + source.acceleration.y = Math.sin(a) * speed; + source.maxVelocity.x = xSpeedMax; + source.maxVelocity.y = ySpeedMax; + }; + Motion.prototype.moveTowardsPoint = /** + * Sets the x/y velocity on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
+ * Timings are approximate due to the way Flash timers work, and irrespective of SWF frame rate. Allow for a variance of +- 50ms.
+ * The source object doesn't stop moving automatically should it ever reach the destination coordinates.
+ * + * @param {GameObject} source The Sprite to move + * @param {Point} target The Point coordinates to move the source Sprite towards + * @param {number} speed The speed it will move, in pixels per second (default is 60 pixels/sec) + * @param {number} maxTime Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the source will arrive at destination in the given number of ms + */ + function (source, target, speed, maxTime) { + if (typeof speed === "undefined") { speed = 60; } + if (typeof maxTime === "undefined") { maxTime = 0; } + var a = this.angleBetweenPoint(source, target); + if(maxTime > 0) { + var d = this.distanceToPoint(source, target); + // We know how many pixels we need to move, but how fast? + speed = d / (maxTime / 1000); + } + source.velocity.x = Math.cos(a) * speed; + source.velocity.y = Math.sin(a) * speed; + }; + Motion.prototype.accelerateTowardsPoint = /** + * Sets the x/y acceleration on the source Sprite so it will move towards the target coordinates at the speed given (in pixels per second)
+ * You must give a maximum speed value, beyond which the Sprite won't go any faster.
+ * If you don't need acceleration look at moveTowardsPoint() instead. + * + * @param {GameObject} source The Sprite on which the acceleration will be set + * @param {Point} target The Point coordinates to move the source Sprite towards + * @param {number} speed The speed it will accelerate in pixels per second + * @param {number} xSpeedMax The maximum speed in pixels per second in which the sprite can move horizontally + * @param {number} ySpeedMax The maximum speed in pixels per second in which the sprite can move vertically + */ + function (source, target, speed, xSpeedMax, ySpeedMax) { + var a = this.angleBetweenPoint(source, target); + source.velocity.x = 0; + source.velocity.y = 0; + source.acceleration.x = Math.cos(a) * speed; + source.acceleration.y = Math.sin(a) * speed; + source.maxVelocity.x = xSpeedMax; + source.maxVelocity.y = ySpeedMax; + }; + Motion.prototype.distanceBetween = /** + * Find the distance (in pixels, rounded) between two Sprites, taking their origin into account + * + * @param {GameObject} a The first Sprite + * @param {GameObject} b The second Sprite + * @return {number} int Distance (in pixels) + */ + function (a, b) { + var dx = (a.x + a.origin.x) - (b.x + b.origin.x); + var dy = (a.y + a.origin.y) - (b.y + b.origin.y); + return this._game.math.vectorLength(dx, dy); + }; + Motion.prototype.distanceToPoint = /** + * Find the distance (in pixels, rounded) from an Sprite to the given Point, taking the source origin into account + * + * @param {GameObject} a The Sprite + * @param {Point} target The Point + * @return {number} Distance (in pixels) + */ + function (a, target) { + var dx = (a.x + a.origin.x) - (target.x); + var dy = (a.y + a.origin.y) - (target.y); + return this._game.math.vectorLength(dx, dy); + }; + Motion.prototype.distanceToMouse = /** + * Find the distance (in pixels, rounded) from the object x/y and the mouse x/y + * + * @param {GameObject} a Sprite to test against + * @return {number} The distance between the given sprite and the mouse coordinates + */ + function (a) { + var dx = (a.x + a.origin.x) - this._game.input.x; + var dy = (a.y + a.origin.y) - this._game.input.y; + return this._game.math.vectorLength(dx, dy); + }; + Motion.prototype.angleBetweenPoint = /** + * Find the angle (in radians) between an Sprite and an Point. The source sprite takes its x/y and origin into account. + * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * + * @param {GameObject} a The Sprite to test from + * @param {Point} target The Point to angle the Sprite towards + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + function (a, target, asDegrees) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + var dx = (target.x) - (a.x + a.origin.x); + var dy = (target.y) - (a.y + a.origin.y); + if(asDegrees) { + return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + Motion.prototype.angleBetween = /** + * Find the angle (in radians) between the two Sprite, taking their x/y and origin into account. + * The angle is calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) + * + * @param {GameObject} a The Sprite to test from + * @param {GameObject} b The Sprite to test to + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + function (a, b, asDegrees) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + var dx = (b.x + b.origin.x) - (a.x + a.origin.x); + var dy = (b.y + b.origin.y) - (a.y + a.origin.y); + if(asDegrees) { + return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + Motion.prototype.velocityFromFacing = /** + * Given the GameObject and speed calculate the velocity and return it as an Point based on the direction the sprite is facing + * + * @param {GameObject} parent The Sprite to get the facing value from + * @param {number} speed The speed it will move, in pixels per second sq + * + * @return {Point} An Point where Point.x contains the velocity x value and Point.y contains the velocity y value + */ + function (parent, speed) { + var a; + if(parent.facing == Phaser.Collision.LEFT) { + a = this._game.math.degreesToRadians(180); + } else if(parent.facing == Phaser.Collision.RIGHT) { + a = this._game.math.degreesToRadians(0); + } else if(parent.facing == Phaser.Collision.UP) { + a = this._game.math.degreesToRadians(-90); + } else if(parent.facing == Phaser.Collision.DOWN) { + a = this._game.math.degreesToRadians(90); + } + return new Phaser.Point(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 {GameObject} a The Object to test from + * @param {boolean} asDegrees If you need the value in degrees instead of radians, set to true + * + * @return {number} The angle (in radians unless asDegrees is true) + */ + function (a, asDegrees) { + if (typeof asDegrees === "undefined") { asDegrees = false; } + // In order to get the angle between the object and mouse, we need the objects screen coordinates (rather than world coordinates) + var p = a.getScreenXY(); + var dx = a._game.input.x - p.x; + var dy = a._game.input.y - p.y; + if(asDegrees) { + return this._game.math.radiansToDegrees(Math.atan2(dy, dx)); + } else { + return Math.atan2(dy, dx); + } + }; + return Motion; + })(); + Phaser.Motion = Motion; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Signal.js b/Phaser/Signal.js new file mode 100644 index 00000000..fc6a6e6e --- /dev/null +++ b/Phaser/Signal.js @@ -0,0 +1,250 @@ +/// +/** +* 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 = {})); diff --git a/Phaser/SignalBinding.js b/Phaser/SignalBinding.js new file mode 100644 index 00000000..760df524 --- /dev/null +++ b/Phaser/SignalBinding.js @@ -0,0 +1,113 @@ +/// +/** +* 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 = {})); diff --git a/Phaser/SoundManager.js b/Phaser/SoundManager.js new file mode 100644 index 00000000..76e584e1 --- /dev/null +++ b/Phaser/SoundManager.js @@ -0,0 +1,85 @@ +/// +/// +/** +* Phaser - SoundManager +* +* This is an embroyonic web audio sound management class. There is a lot of work still to do here. +*/ +var Phaser; +(function (Phaser) { + var SoundManager = (function () { + function SoundManager(game) { + this._context = null; + this._game = game; + if(game.device.webaudio == true) { + if(!!window['AudioContext']) { + this._context = new window['AudioContext'](); + } else if(!!window['webkitAudioContext']) { + this._context = new window['webkitAudioContext'](); + } + if(this._context !== null) { + this._gainNode = this._context.createGainNode(); + this._gainNode.connect(this._context.destination); + this._volume = 1; + } + } + } + SoundManager.prototype.mute = function () { + this._gainNode.gain.value = 0; + }; + SoundManager.prototype.unmute = function () { + this._gainNode.gain.value = this._volume; + }; + Object.defineProperty(SoundManager.prototype, "volume", { + get: function () { + return this._volume; + }, + set: function (value) { + this._volume = value; + this._gainNode.gain.value = this._volume; + }, + enumerable: true, + configurable: true + }); + SoundManager.prototype.decode = function (key, callback, sound) { + if (typeof callback === "undefined") { callback = null; } + if (typeof sound === "undefined") { sound = null; } + var soundData = this._game.cache.getSound(key); + if(soundData) { + if(this._game.cache.isSoundDecoded(key) === false) { + var that = this; + this._context.decodeAudioData(soundData, function (buffer) { + that._game.cache.decodedSound(key, buffer); + if(sound) { + sound.setDecodedBuffer(buffer); + } + callback(); + }); + } + } + }; + SoundManager.prototype.play = function (key, volume, loop) { + if (typeof volume === "undefined") { volume = 1; } + if (typeof loop === "undefined") { loop = false; } + if(this._context === null) { + return; + } + var soundData = this._game.cache.getSound(key); + if(soundData) { + // Does the sound need decoding? + if(this._game.cache.isSoundDecoded(key) === true) { + return new Phaser.Sound(this._context, this._gainNode, soundData, volume, loop); + } else { + var tempSound = new Phaser.Sound(this._context, this._gainNode, null, volume, loop); + // this is an async process, so we can return the Sound object anyway, it just won't be playing yet + this.decode(key, function () { + return tempSound.play(); + }, tempSound); + return tempSound; + } + } + }; + return SoundManager; + })(); + Phaser.SoundManager = SoundManager; +})(Phaser || (Phaser = {})); diff --git a/Phaser/Time.js b/Phaser/Time.js new file mode 100644 index 00000000..e2f02e39 --- /dev/null +++ b/Phaser/Time.js @@ -0,0 +1,151 @@ +/// +/** +* Phaser - Time +* +* This is the game clock and it manages elapsed time and calculation of delta values, used for game object motion. +*/ +var Phaser; +(function (Phaser) { + var Time = (function () { + /** + * Time constructor + * Create a new Time. + * + * @param game {Phaser.Game} Current game instance. + */ + function Time(game) { + /** + * Time scale factor. + * Set it to 0.5 for slow motion, to 2.0 makes game twice faster. + * @type {number} + */ + this.timeScale = 1.0; + /** + * Elapsed since last frame. + * @type {number} + */ + this.elapsed = 0; + /** + * Game time counter. + * @property time + * @type {number} + */ + this.time = 0; + /** + * Time of current frame. + * @property now + * @type {number} + */ + this.now = 0; + /** + * Elapsed time since last frame. + * @property delta + * @type {number} + */ + this.delta = 0; + /** + * Frames per second. + * @type {number} + */ + this.fps = 0; + /** + * Minimal fps. + * @type {number} + */ + this.fpsMin = 1000; + /** + * Maximal fps. + * @type {number} + */ + this.fpsMax = 0; + /** + * Mininal duration between 2 frames. + * @type {number} + */ + this.msMin = 1000; + /** + * Maximal duration between 2 frames. + * @type {number} + */ + this.msMax = 0; + /** + * How many frames in last second. + * @type {number} + */ + this.frames = 0; + /** + * Time of last second. + * @type {number} + */ + this._timeLastSecond = 0; + this._started = 0; + this._timeLastSecond = this._started; + this.time = this._started; + this._game = game; + } + Object.defineProperty(Time.prototype, "totalElapsedSeconds", { + get: /** + * + * @method totalElapsedSeconds + * @return {Number} + */ + function () { + return (this.now - this._started) * 0.001; + }, + enumerable: true, + configurable: true + }); + Time.prototype.update = /** + * Update clock and calculate the fps. + * This is called automatically by Game._raf + * @method update + * @param {number} raf The current timestamp, either performance.now or Date.now + */ + function (raf) { + this.now = raf// mark + ; + //this.now = Date.now(); // mark + this.delta = this.now - this.time// elapsedMS + ; + this.msMin = Math.min(this.msMin, this.delta); + this.msMax = Math.max(this.msMax, this.delta); + this.frames++; + if(this.now > this._timeLastSecond + 1000) { + this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond)); + this.fpsMin = Math.min(this.fpsMin, this.fps); + this.fpsMax = Math.max(this.fpsMax, this.fps); + this._timeLastSecond = this.now; + this.frames = 0; + } + this.time = this.now// _total + ; + }; + Time.prototype.elapsedSince = /** + * How long has passed since given time. + * @method elapsedSince + * @param {number} since The time you want to measure. + * @return {number} Duration between given time and now. + */ + function (since) { + return this.now - since; + }; + Time.prototype.elapsedSecondsSince = /** + * How long has passed since give time (in seconds). + * @method elapsedSecondsSince + * @param {number} since The time you want to measure (in seconds). + * @return {number} Duration between given time and now (in seconds). + */ + function (since) { + return (this.now - since) * 0.001; + }; + Time.prototype.reset = /** + * Set the start time to now. + * @method reset + */ + function () { + this._started = this.now; + }; + return Time; + })(); + Phaser.Time = Time; +})(Phaser || (Phaser = {})); diff --git a/Phaser/TweenManager.js b/Phaser/TweenManager.js new file mode 100644 index 00000000..f9889ea0 --- /dev/null +++ b/Phaser/TweenManager.js @@ -0,0 +1,58 @@ +/// +/// +/** +* Phaser - TweenManager +* +* The Game has a single instance of the TweenManager through which all Tween objects are created and updated. +* Tweens are hooked into the game clock and pause system, adjusting based on the game state. +* TweenManager is based heavily on tween.js by sole (http://soledadpenades.com). +* I converted it to TypeScript, swapped the callbacks for signals and patched a few issues with regard +* to properties and completion errors. Please see https://github.com/sole/tween.js for a full list of contributors. +*/ +var Phaser; +(function (Phaser) { + var TweenManager = (function () { + function TweenManager(game) { + this._game = game; + this._tweens = []; + } + TweenManager.prototype.getAll = function () { + return this._tweens; + }; + TweenManager.prototype.removeAll = function () { + this._tweens.length = 0; + }; + TweenManager.prototype.create = function (object) { + return new Phaser.Tween(object, this._game); + }; + TweenManager.prototype.add = function (tween) { + tween.parent = this._game; + this._tweens.push(tween); + return tween; + }; + TweenManager.prototype.remove = function (tween) { + var i = this._tweens.indexOf(tween); + if(i !== -1) { + this._tweens.splice(i, 1); + } + }; + TweenManager.prototype.update = function () { + if(this._tweens.length === 0) { + return false; + } + var i = 0; + var numTweens = this._tweens.length; + while(i < numTweens) { + if(this._tweens[i].update(this._game.time.now)) { + i++; + } else { + this._tweens.splice(i, 1); + numTweens--; + } + } + return true; + }; + return TweenManager; + })(); + Phaser.TweenManager = TweenManager; +})(Phaser || (Phaser = {})); diff --git a/Phaser/gameobjects/Emitter.js b/Phaser/gameobjects/Emitter.js new file mode 100644 index 00000000..ec72ceaf --- /dev/null +++ b/Phaser/gameobjects/Emitter.js @@ -0,0 +1,285 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/** +* Phaser - Emitter +* +* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for +* continuous effects like rain and fire. All it really does is launch Particle objects out +* at set intervals, and fixes their positions and velocities accorindgly. +*/ +var Phaser; +(function (Phaser) { + var Emitter = (function (_super) { + __extends(Emitter, _super); + /** + * Creates a new Emitter object at a specific position. + * Does NOT automatically generate or attach particles! + * + * @param x {number} The X position of the emitter. + * @param y {number} The Y position of the emitter. + * @param [size] {number} Specifies a maximum capacity for this emitter. + */ + function Emitter(game, x, y, size) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof size === "undefined") { size = 0; } + _super.call(this, game, size); + this.x = x; + this.y = y; + this.width = 0; + this.height = 0; + this.minParticleSpeed = new MicroPoint(-100, -100); + this.maxParticleSpeed = new MicroPoint(100, 100); + this.minRotation = -360; + this.maxRotation = 360; + this.gravity = 0; + this.particleClass = null; + this.particleDrag = new MicroPoint(); + this.frequency = 0.1; + this.lifespan = 3; + this.bounce = 0; + this._quantity = 0; + this._counter = 0; + this._explode = true; + this.on = false; + this._point = new MicroPoint(); + } + Emitter.prototype.destroy = /** + * Clean up memory. + */ + function () { + this.minParticleSpeed = null; + this.maxParticleSpeed = null; + this.particleDrag = null; + this.particleClass = null; + this._point = null; + _super.prototype.destroy.call(this); + }; + Emitter.prototype.makeParticles = /** + * This function generates a new array of particle sprites to attach to the emitter. + * + * @param graphics If you opted to not pre-configure an array of Sprite objects, you can simply pass in a particle image or sprite sheet. + * @param quantity {number} The number of particles to generate when using the "create from image" option. + * @param multiple {boolean} Whether the image in the Graphics param is a single particle or a bunch of particles (if it's a bunch, they need to be square!). + * @param collide {number} Whether the particles should be flagged as not 'dead' (non-colliding particles are higher performance). 0 means no collisions, 0-1 controls scale of particle's bounding box. + * + * @return This Emitter instance (nice for chaining stuff together, if you're into that). + */ + function (graphics, quantity, multiple, collide) { + if (typeof quantity === "undefined") { quantity = 50; } + if (typeof multiple === "undefined") { multiple = false; } + if (typeof collide === "undefined") { collide = 0; } + this.maxSize = quantity; + var totalFrames = 1; + /* + if(Multiple) + { + var sprite:Sprite = new Sprite(this._game); + sprite.loadGraphic(Graphics,true); + totalFrames = sprite.frames; + sprite.destroy(); + } + */ + var randomFrame; + var particle; + var i = 0; + while(i < quantity) { + if(this.particleClass == null) { + particle = new Phaser.Particle(this._game); + } else { + particle = new this.particleClass(this._game); + } + if(multiple) { + /* + randomFrame = this._game.math.random()*totalFrames; + if(BakedRotations > 0) + particle.loadRotatedGraphic(Graphics,BakedRotations,randomFrame); + else + { + particle.loadGraphic(Graphics,true); + particle.frame = randomFrame; + } + */ + } else { + /* + if (BakedRotations > 0) + particle.loadRotatedGraphic(Graphics,BakedRotations); + else + particle.loadGraphic(Graphics); + */ + if(graphics) { + particle.loadGraphic(graphics); + } + } + if(collide > 0) { + particle.allowCollisions = Phaser.Collision.ANY; + particle.width *= collide; + particle.height *= collide; + //particle.centerOffsets(); + } else { + particle.allowCollisions = Phaser.Collision.NONE; + } + particle.exists = false; + this.add(particle); + i++; + } + return this; + }; + Emitter.prototype.update = /** + * Called automatically by the game loop, decides when to launch particles and when to "die". + */ + function () { + if(this.on) { + if(this._explode) { + this.on = false; + var i = 0; + var l = this._quantity; + if((l <= 0) || (l > this.length)) { + l = this.length; + } + while(i < l) { + this.emitParticle(); + i++; + } + this._quantity = 0; + } else { + this._timer += this._game.time.elapsed; + while((this.frequency > 0) && (this._timer > this.frequency) && this.on) { + this._timer -= this.frequency; + this.emitParticle(); + if((this._quantity > 0) && (++this._counter >= this._quantity)) { + this.on = false; + this._quantity = 0; + } + } + } + } + _super.prototype.update.call(this); + }; + Emitter.prototype.kill = /** + * Call this function to turn off all the particles and the emitter. + */ + function () { + this.on = false; + _super.prototype.kill.call(this); + }; + Emitter.prototype.start = /** + * Call this function to start emitting particles. + * + * @param explode {boolean} Whether the particles should all burst out at once. + * @param lifespan {number} How long each particle lives once emitted. 0 = forever. + * @param frequency {number} Ignored if Explode is set to true. Frequency is how often to emit a particle. 0 = never emit, 0.1 = 1 particle every 0.1 seconds, 5 = 1 particle every 5 seconds. + * @param quantity {number} How many particles to launch. 0 = "all of the particles". + */ + function (explode, lifespan, frequency, quantity) { + if (typeof explode === "undefined") { explode = true; } + if (typeof lifespan === "undefined") { lifespan = 0; } + if (typeof frequency === "undefined") { frequency = 0.1; } + if (typeof quantity === "undefined") { quantity = 0; } + this.revive(); + this.visible = true; + this.on = true; + this._explode = explode; + this.lifespan = lifespan; + this.frequency = frequency; + this._quantity += quantity; + this._counter = 0; + this._timer = 0; + }; + Emitter.prototype.emitParticle = /** + * This function can be used both internally and externally to emit the next particle. + */ + function () { + var particle = this.recycle(Phaser.Particle); + particle.lifespan = this.lifespan; + particle.elasticity = this.bounce; + particle.reset(this.x - (particle.width >> 1) + this._game.math.random() * this.width, this.y - (particle.height >> 1) + this._game.math.random() * this.height); + particle.visible = true; + if(this.minParticleSpeed.x != this.maxParticleSpeed.x) { + particle.velocity.x = this.minParticleSpeed.x + this._game.math.random() * (this.maxParticleSpeed.x - this.minParticleSpeed.x); + } else { + particle.velocity.x = this.minParticleSpeed.x; + } + if(this.minParticleSpeed.y != this.maxParticleSpeed.y) { + particle.velocity.y = this.minParticleSpeed.y + this._game.math.random() * (this.maxParticleSpeed.y - this.minParticleSpeed.y); + } else { + particle.velocity.y = this.minParticleSpeed.y; + } + particle.acceleration.y = this.gravity; + if(this.minRotation != this.maxRotation && this.minRotation !== 0 && this.maxRotation !== 0) { + particle.angularVelocity = this.minRotation + this._game.math.random() * (this.maxRotation - this.minRotation); + } else { + particle.angularVelocity = this.minRotation; + } + if(particle.angularVelocity != 0) { + particle.angle = this._game.math.random() * 360 - 180; + } + particle.drag.x = this.particleDrag.x; + particle.drag.y = this.particleDrag.y; + particle.onEmit(); + }; + Emitter.prototype.setSize = /** + * A more compact way of setting the width and height of the emitter. + * + * @param width {number} The desired width of the emitter (particles are spawned randomly within these dimensions). + * @param height {number} The desired height of the emitter. + */ + function (width, height) { + this.width = width; + this.height = height; + }; + Emitter.prototype.setXSpeed = /** + * A more compact way of setting the X velocity range of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. + */ + function (min, max) { + if (typeof min === "undefined") { min = 0; } + if (typeof max === "undefined") { max = 0; } + this.minParticleSpeed.x = min; + this.maxParticleSpeed.x = max; + }; + Emitter.prototype.setYSpeed = /** + * A more compact way of setting the Y velocity range of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. + */ + function (min, max) { + if (typeof min === "undefined") { min = 0; } + if (typeof max === "undefined") { max = 0; } + this.minParticleSpeed.y = min; + this.maxParticleSpeed.y = max; + }; + Emitter.prototype.setRotation = /** + * A more compact way of setting the angular velocity constraints of the emitter. + * + * @param Min {number} The minimum value for this range. + * @param Max {number} The maximum value for this range. + */ + function (min, max) { + if (typeof min === "undefined") { min = 0; } + if (typeof max === "undefined") { max = 0; } + this.minRotation = min; + this.maxRotation = max; + }; + Emitter.prototype.at = /** + * Change the emitter's midpoint to match the midpoint of a Object. + * + * @param Object {object} The Object that you want to sync up with. + */ + function (object) { + object.getMidpoint(this._point); + this.x = this._point.x - (this.width >> 1); + this.y = this._point.y - (this.height >> 1); + }; + return Emitter; + })(Phaser.Group); + Phaser.Emitter = Emitter; +})(Phaser || (Phaser = {})); diff --git a/Phaser/gameobjects/GameObject.js b/Phaser/gameobjects/GameObject.js new file mode 100644 index 00000000..6826946d --- /dev/null +++ b/Phaser/gameobjects/GameObject.js @@ -0,0 +1,534 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/// +/// +/** +* Phaser - GameObject +* +* This is the base GameObject on which all other game objects are derived. It contains all the logic required for position, +* motion, size, collision and input. +*/ +var Phaser; +(function (Phaser) { + var GameObject = (function (_super) { + __extends(GameObject, _super); + /** + * GameObject constructor + * + * Create a new GameObject object at specific position with specific width and height. + * + * @param [x] {number} The x position of the object. + * @param [y] {number} The y position of the object. + * @param [width] {number} The width of the object. + * @param [height] {number} The height of the object. + */ + function GameObject(game, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 16; } + if (typeof height === "undefined") { height = 16; } + _super.call(this, game); + /** + * Angle of this object. + * @type {number} + */ + this._angle = 0; + /** + * What action will be performed when object is out of the worldBounds. + * This will default to GameObject.OUT_OF_BOUNDS_STOP. + * @type {number} + */ + this.outOfBoundsAction = 0; + /** + * Z-order value of the object. + */ + this.z = 0; + /** + * This value is added to the angle of the GameObject. + * For example if you had a sprite drawn facing straight up then you could set + * rotationOffset to 90 and it would correspond correctly with Phasers rotation system + * @type {number} + */ + this.rotationOffset = 0; + /** + * Controls if the GameObject is rendered rotated or not. + * If renderRotation is false then the object can still rotate but it will never be rendered rotated. + * @type {boolean} + */ + this.renderRotation = true; + /** + * Set this to false if you want to skip the automatic motion/movement stuff + * (see updateMotion()). + * @type {boolean} + */ + this.moves = true; + // Input + this.inputEnabled = false; + this._inputOver = false; + this.canvas = game.stage.canvas; + this.context = game.stage.context; + this.frameBounds = new Rectangle(x, y, width, height); + this.exists = true; + this.active = true; + this.visible = true; + this.alive = true; + this.isGroup = false; + this.alpha = 1; + this.scale = new MicroPoint(1, 1); + this.last = new MicroPoint(x, y); + this.align = GameObject.ALIGN_TOP_LEFT; + this.mass = 1; + this.elasticity = 0; + this.health = 1; + this.immovable = false; + this.moves = true; + this.worldBounds = null; + this.touching = Collision.NONE; + this.wasTouching = Collision.NONE; + this.allowCollisions = Collision.ANY; + this.velocity = new MicroPoint(); + this.acceleration = new MicroPoint(); + this.drag = new MicroPoint(); + this.maxVelocity = new MicroPoint(10000, 10000); + this.angle = 0; + this.angularVelocity = 0; + this.angularAcceleration = 0; + this.angularDrag = 0; + this.maxAngular = 10000; + this.cameraBlacklist = []; + this.scrollFactor = new MicroPoint(1, 1); + this.collisionMask = new CollisionMask(game, this, x, y, width, height); + } + GameObject.ALIGN_TOP_LEFT = 0; + GameObject.ALIGN_TOP_CENTER = 1; + GameObject.ALIGN_TOP_RIGHT = 2; + GameObject.ALIGN_CENTER_LEFT = 3; + GameObject.ALIGN_CENTER = 4; + GameObject.ALIGN_CENTER_RIGHT = 5; + GameObject.ALIGN_BOTTOM_LEFT = 6; + GameObject.ALIGN_BOTTOM_CENTER = 7; + GameObject.ALIGN_BOTTOM_RIGHT = 8; + GameObject.OUT_OF_BOUNDS_STOP = 0; + GameObject.OUT_OF_BOUNDS_KILL = 1; + GameObject.prototype.preUpdate = /** + * Pre-update is called right before update() on each object in the game loop. + */ + function () { + this.last.x = this.frameBounds.x; + this.last.y = this.frameBounds.y; + this.collisionMask.preUpdate(); + }; + GameObject.prototype.update = /** + * Override this function to update your class's position and appearance. + */ + function () { + }; + GameObject.prototype.postUpdate = /** + * Automatically called after update() by the game loop. + */ + function () { + if(this.moves) { + this.updateMotion(); + } + if(this.worldBounds != null) { + if(this.outOfBoundsAction == Phaser.GameObject.OUT_OF_BOUNDS_KILL) { + if(this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom) { + this.kill(); + } + } else { + if(this.x < this.worldBounds.x) { + this.x = this.worldBounds.x; + } else if(this.x > this.worldBounds.right) { + this.x = this.worldBounds.right; + } + if(this.y < this.worldBounds.y) { + this.y = this.worldBounds.y; + } else if(this.y > this.worldBounds.bottom) { + this.y = this.worldBounds.bottom; + } + } + } + this.collisionMask.update(); + if(this.inputEnabled) { + this.updateInput(); + } + this.wasTouching = this.touching; + this.touching = Phaser.Collision.NONE; + }; + GameObject.prototype.updateInput = /** + * Update input. + */ + function () { + }; + GameObject.prototype.updateMotion = /** + * Internal function for updating the position and speed of this object. + */ + function () { + var delta; + var velocityDelta; + velocityDelta = (this._game.motion.computeVelocity(this.angularVelocity, this.angularAcceleration, this.angularDrag, this.maxAngular) - this.angularVelocity) / 2; + this.angularVelocity += velocityDelta; + this._angle += this.angularVelocity * this._game.time.elapsed; + this.angularVelocity += velocityDelta; + velocityDelta = (this._game.motion.computeVelocity(this.velocity.x, this.acceleration.x, this.drag.x, this.maxVelocity.x) - this.velocity.x) / 2; + this.velocity.x += velocityDelta; + delta = this.velocity.x * this._game.time.elapsed; + this.velocity.x += velocityDelta; + this.frameBounds.x += delta; + velocityDelta = (this._game.motion.computeVelocity(this.velocity.y, this.acceleration.y, this.drag.y, this.maxVelocity.y) - this.velocity.y) / 2; + this.velocity.y += velocityDelta; + delta = this.velocity.y * this._game.time.elapsed; + this.velocity.y += velocityDelta; + this.frameBounds.y += delta; + }; + GameObject.prototype.overlaps = /** + * Checks to see if some GameObject overlaps this GameObject or Group. + * If the group has a LOT of things in it, it might be faster to use Collision.overlaps(). + * WARNING: Currently tilemaps do NOT support screen space overlap checks! + * + * @param objectOrGroup {object} The object or group being tested. + * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether or not the objects overlap this. + */ + function (objectOrGroup, inScreenSpace, camera) { + if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } + if (typeof camera === "undefined") { camera = null; } + if(objectOrGroup.isGroup) { + var results = false; + var i = 0; + var members = objectOrGroup.members; + while(i < length) { + if(this.overlaps(members[i++], inScreenSpace, camera)) { + results = true; + } + } + return results; + } + if(!inScreenSpace) { + return (objectOrGroup.x + objectOrGroup.width > this.x) && (objectOrGroup.x < this.x + this.width) && (objectOrGroup.y + objectOrGroup.height > this.y) && (objectOrGroup.y < this.y + this.height); + } + if(camera == null) { + camera = this._game.camera; + } + var objectScreenPos = objectOrGroup.getScreenXY(null, camera); + this.getScreenXY(this._point, camera); + return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); + }; + GameObject.prototype.overlapsAt = /** + * Checks to see if this GameObject were located at the given position, would it overlap the GameObject or Group? + * This is distinct from overlapsPoint(), which just checks that point, rather than taking the object's size numbero account. + * WARNING: Currently tilemaps do NOT support screen space overlap checks! + * + * @param X {number} The X position you want to check. Pretends this object (the caller, not the parameter) is located here. + * @param Y {number} The Y position you want to check. Pretends this object (the caller, not the parameter) is located here. + * @param objectOrGroup {object} The object or group being tested. + * @param inScreenSpace {boolean} Whether to take scroll factors numbero account when checking for overlap. Default is false, or "only compare in world space." + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether or not the two objects overlap. + */ + function (X, Y, objectOrGroup, inScreenSpace, camera) { + if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } + if (typeof camera === "undefined") { camera = null; } + if(objectOrGroup.isGroup) { + var results = false; + var basic; + var i = 0; + var members = objectOrGroup.members; + while(i < length) { + if(this.overlapsAt(X, Y, members[i++], inScreenSpace, camera)) { + results = true; + } + } + return results; + } + if(!inScreenSpace) { + return (objectOrGroup.x + objectOrGroup.width > X) && (objectOrGroup.x < X + this.width) && (objectOrGroup.y + objectOrGroup.height > Y) && (objectOrGroup.y < Y + this.height); + } + if(camera == null) { + camera = this._game.camera; + } + var objectScreenPos = objectOrGroup.getScreenXY(null, Phaser.Camera); + this._point.x = X - camera.scroll.x * this.scrollFactor.x//copied from getScreenXY() + ; + this._point.y = Y - camera.scroll.y * this.scrollFactor.y; + this._point.x += (this._point.x > 0) ? 0.0000001 : -0.0000001; + this._point.y += (this._point.y > 0) ? 0.0000001 : -0.0000001; + return (objectScreenPos.x + objectOrGroup.width > this._point.x) && (objectScreenPos.x < this._point.x + this.width) && (objectScreenPos.y + objectOrGroup.height > this._point.y) && (objectScreenPos.y < this._point.y + this.height); + }; + GameObject.prototype.overlapsPoint = /** + * Checks to see if a point in 2D world space overlaps this GameObject. + * + * @param point {Point} The point in world space you want to check. + * @param inScreenSpace {boolean} Whether to take scroll factors into account when checking for overlap. + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return Whether or not the point overlaps this object. + */ + function (point, inScreenSpace, camera) { + if (typeof inScreenSpace === "undefined") { inScreenSpace = false; } + if (typeof camera === "undefined") { camera = null; } + if(!inScreenSpace) { + return (point.x > this.x) && (point.x < this.x + this.width) && (point.y > this.y) && (point.y < this.y + this.height); + } + if(camera == null) { + camera = this._game.camera; + } + var X = point.x - camera.scroll.x; + var Y = point.y - camera.scroll.y; + this.getScreenXY(this._point, camera); + return (X > this._point.x) && (X < this._point.x + this.width) && (Y > this._point.y) && (Y < this._point.y + this.height); + }; + GameObject.prototype.onScreen = /** + * Check and see if this object is currently on screen. + * + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {boolean} Whether the object is on screen or not. + */ + function (camera) { + if (typeof camera === "undefined") { camera = null; } + if(camera == null) { + camera = this._game.camera; + } + this.getScreenXY(this._point, camera); + return (this._point.x + this.width > 0) && (this._point.x < camera.width) && (this._point.y + this.height > 0) && (this._point.y < camera.height); + }; + GameObject.prototype.getScreenXY = /** + * Call this to figure out the on-screen position of the object. + * + * @param point {Point} Takes a MicroPoint object and assigns the post-scrolled X and Y values of this object to it. + * @param camera {Camera} Specify which game camera you want. If null getScreenXY() will just grab the first global camera. + * + * @return {MicroPoint} The MicroPoint you passed in, or a new Point if you didn't pass one, containing the screen X and Y position of this object. + */ + function (point, camera) { + if (typeof point === "undefined") { point = null; } + if (typeof camera === "undefined") { camera = null; } + if(point == null) { + point = new Phaser.MicroPoint(); + } + if(camera == null) { + camera = this._game.camera; + } + point.x = this.x - camera.scroll.x * this.scrollFactor.x; + point.y = this.y - camera.scroll.y * this.scrollFactor.y; + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + return point; + }; + Object.defineProperty(GameObject.prototype, "solid", { + get: /** + * Whether the object collides or not. For more control over what directions + * the object will collide from, use collision constants (like LEFT, FLOOR, etc) + * to set the value of allowCollisions directly. + */ + function () { + return (this.allowCollisions & Phaser.Collision.ANY) > Phaser.Collision.NONE; + }, + set: function (value) { + if(value) { + this.allowCollisions = Phaser.Collision.ANY; + } else { + this.allowCollisions = Phaser.Collision.NONE; + } + }, + enumerable: true, + configurable: true + }); + GameObject.prototype.getMidpoint = /** + * Retrieve the midpoint of this object in world coordinates. + * + * @param point {Point} Allows you to pass in an existing Point object if you're so inclined. Otherwise a new one is created. + * + * @return {MicroPoint} A Point object containing the midpoint of this object in world coordinates. + */ + function (point) { + if (typeof point === "undefined") { point = null; } + if(point == null) { + point = new Phaser.MicroPoint(); + } + point.copyFrom(this.frameBounds.center); + return point; + }; + GameObject.prototype.reset = /** + * Handy for reviving game objects. + * Resets their existence flags and position. + * + * @param x {number} The new X position of this object. + * @param y {number} The new Y position of this object. + */ + function (x, y) { + this.revive(); + this.touching = Phaser.Collision.NONE; + this.wasTouching = Phaser.Collision.NONE; + this.x = x; + this.y = y; + this.last.x = x; + this.last.y = y; + this.velocity.x = 0; + this.velocity.y = 0; + }; + GameObject.prototype.isTouching = /** + * Handy for checking if this object is touching a particular surface. + * For slightly better performance you can just & the value directly into touching. + * However, this method is good for readability and accessibility. + * + * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). + * + * @return {boolean} Whether the object is touching an object in (any of) the specified direction(s) this frame. + */ + function (direction) { + return (this.touching & direction) > Phaser.Collision.NONE; + }; + GameObject.prototype.justTouched = /** + * Handy function for checking if this object just landed on a particular surface. + * + * @param Direction {number} Any of the collision flags (e.g. LEFT, FLOOR, etc). + * + * @returns {boolean} Whether the object just landed on any specicied surfaces. + */ + function (direction) { + return ((this.touching & direction) > Phaser.Collision.NONE) && ((this.wasTouching & direction) <= Phaser.Collision.NONE); + }; + GameObject.prototype.hurt = /** + * Reduces the "health" variable of this sprite by the amount specified in Damage. + * Calls kill() if health drops to or below zero. + * + * @param Damage {number} How much health to take away (use a negative number to give a health bonus). + */ + function (damage) { + this.health = this.health - damage; + if(this.health <= 0) { + this.kill(); + } + }; + GameObject.prototype.setBounds = /** + * Set the world bounds that this GameObject can exist within. By default a GameObject can exist anywhere + * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) + * it can be stopped from leaving the world, or a section of it. + * + * @param x {number} x position of the bound + * @param y {number} y position of the bound + * @param width {number} width of its bound + * @param height {number} height of its bound + */ + function (x, y, width, height) { + this.worldBounds = new Phaser.Quad(x, y, width, height); + }; + GameObject.prototype.setBoundsFromWorld = /** + * Set the world bounds that this GameObject can exist within based on the size of the current game world. + * + * @param action {number} The action to take if the object hits the world bounds, either OUT_OF_BOUNDS_KILL or OUT_OF_BOUNDS_STOP + */ + function (action) { + if (typeof action === "undefined") { action = Phaser.GameObject.OUT_OF_BOUNDS_STOP; } + this.setBounds(this._game.world.bounds.x, this._game.world.bounds.y, this._game.world.bounds.width, this._game.world.bounds.height); + this.outOfBoundsAction = action; + }; + GameObject.prototype.hideFromCamera = /** + * If you do not wish this object to be visible to a specific camera, pass the camera here. + * + * @param camera {Camera} The specific camera. + */ + function (camera) { + if(this.cameraBlacklist.indexOf(camera.ID) == -1) { + this.cameraBlacklist.push(camera.ID); + } + }; + GameObject.prototype.showToCamera = /** + * Make this object only visible to a specific camera. + * + * @param camera {Camera} The camera you wish it to be visible. + */ + function (camera) { + if(this.cameraBlacklist.indexOf(camera.ID) !== -1) { + this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1); + } + }; + GameObject.prototype.clearCameraList = /** + * This clears the camera black list, making the GameObject visible to all cameras. + */ + function () { + this.cameraBlacklist.length = 0; + }; + GameObject.prototype.destroy = /** + * Clean up memory. + */ + function () { + }; + GameObject.prototype.setPosition = function (x, y) { + this.x = x; + this.y = y; + }; + Object.defineProperty(GameObject.prototype, "x", { + get: function () { + return this.frameBounds.x; + }, + set: function (value) { + this.frameBounds.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GameObject.prototype, "y", { + get: function () { + return this.frameBounds.y; + }, + set: function (value) { + this.frameBounds.y = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GameObject.prototype, "rotation", { + get: function () { + return this._angle; + }, + set: function (value) { + this._angle = this._game.math.wrap(value, 360, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GameObject.prototype, "angle", { + get: function () { + return this._angle; + }, + set: function (value) { + this._angle = this._game.math.wrap(value, 360, 0); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GameObject.prototype, "width", { + get: function () { + return this.frameBounds.width; + }, + set: function (value) { + this.frameBounds.width = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GameObject.prototype, "height", { + get: function () { + return this.frameBounds.height; + }, + set: function (value) { + this.frameBounds.height = value; + }, + enumerable: true, + configurable: true + }); + return GameObject; + })(Phaser.Basic); + Phaser.GameObject = GameObject; +})(Phaser || (Phaser = {})); diff --git a/Phaser/gameobjects/GeomSprite.js b/Phaser/gameobjects/GeomSprite.js new file mode 100644 index 00000000..4d08929f --- /dev/null +++ b/Phaser/gameobjects/GeomSprite.js @@ -0,0 +1,449 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/** +* Phaser - GeomSprite +* +* A GeomSprite is a special kind of GameObject that contains a base geometry class (Circle, Line, Point, Rectangle). +* They can be rendered in the game and used for collision just like any other game object. Display of them is controlled +* via the lineWidth / lineColor / fillColor and renderOutline / renderFill properties. +*/ +var Phaser; +(function (Phaser) { + var GeomSprite = (function (_super) { + __extends(GeomSprite, _super); + /** + * GeomSprite constructor + * Create a new GeomSprite. + * + * @param game {Phaser.Game} Current game instance. + * @param [x] {number} the initial x position of the sprite. + * @param [y] {number} the initial y position of the sprite. + */ + function GeomSprite(game, x, y) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + _super.call(this, game, x, y); + // local rendering related temp vars to help avoid gc spikes + this._dx = 0; + this._dy = 0; + this._dw = 0; + this._dh = 0; + /** + * Geom type of this sprite. (available: UNASSIGNED, CIRCLE, LINE, POINT, RECTANGLE) + * @type {number} + */ + this.type = 0; + /** + * Render outline of this sprite or not. (default is true) + * @type {boolean} + */ + this.renderOutline = true; + /** + * Fill the shape or not. (default is true) + * @type {boolean} + */ + this.renderFill = true; + /** + * Width of outline. (default is 1) + * @type {number} + */ + this.lineWidth = 1; + /** + * Width of outline. (default is 1) + * @type {number} + */ + this.lineColor = 'rgb(0,255,0)'; + /** + * The color of the filled area in rgb or rgba string format + * @type {string} Defaults to rgb(0,100,0) - a green color + */ + this.fillColor = 'rgb(0,100,0)'; + this.type = GeomSprite.UNASSIGNED; + return this; + } + GeomSprite.UNASSIGNED = 0; + GeomSprite.CIRCLE = 1; + GeomSprite.LINE = 2; + GeomSprite.POINT = 3; + GeomSprite.RECTANGLE = 4; + GeomSprite.POLYGON = 5; + GeomSprite.prototype.loadCircle = /** + * Just like Sprite.loadGraphic(), this will load a circle and set its shape to Circle. + * @param circle {Circle} Circle geometry define. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (circle) { + this.refresh(); + this.circle = circle; + this.type = Phaser.GeomSprite.CIRCLE; + return this; + }; + GeomSprite.prototype.loadLine = /** + * Just like Sprite.loadGraphic(), this will load a line and set its shape to Line. + * @param line {Line} Line geometry define. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (line) { + this.refresh(); + this.line = line; + this.type = Phaser.GeomSprite.LINE; + return this; + }; + GeomSprite.prototype.loadPoint = /** + * Just like Sprite.loadGraphic(), this will load a point and set its shape to Point. + * @param point {Point} Point geometry define. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (point) { + this.refresh(); + this.point = point; + this.type = Phaser.GeomSprite.POINT; + return this; + }; + GeomSprite.prototype.loadRectangle = /** + * Just like Sprite.loadGraphic(), this will load a rect and set its shape to Rectangle. + * @param rect {Rectangle} Rectangle geometry define. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (rect) { + this.refresh(); + this.rect = rect; + this.type = Phaser.GeomSprite.RECTANGLE; + return this; + }; + GeomSprite.prototype.createCircle = /** + * Create a circle shape with specific diameter. + * @param diameter {number} Diameter of the circle. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (diameter) { + this.refresh(); + this.circle = new Phaser.Circle(this.x, this.y, diameter); + this.type = Phaser.GeomSprite.CIRCLE; + this.frameBounds.setTo(this.circle.x - this.circle.radius, this.circle.y - this.circle.radius, this.circle.diameter, this.circle.diameter); + return this; + }; + GeomSprite.prototype.createLine = /** + * Create a line shape with specific end point. + * @param x {number} X position of the end point. + * @param y {number} Y position of the end point. + * @return {GeomSprite} GeomSprite instance itself. + */ + function (x, y) { + this.refresh(); + this.line = new Phaser.Line(this.x, this.y, x, y); + this.type = Phaser.GeomSprite.LINE; + this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); + return this; + }; + GeomSprite.prototype.createPoint = /** + * Create a point shape at spriter's position. + * @return {GeomSprite} GeomSprite instance itself. + */ + function () { + this.refresh(); + this.point = new Phaser.Point(this.x, this.y); + this.type = Phaser.GeomSprite.POINT; + this.frameBounds.width = 1; + this.frameBounds.height = 1; + return this; + }; + GeomSprite.prototype.createRectangle = /** + * Create a rectangle shape of the given width and height size + * @param width {Number} Width of the rectangle + * @param height {Number} Height of the rectangle + * @return {GeomSprite} GeomSprite instance. + */ + function (width, height) { + this.refresh(); + this.rect = new Phaser.Rectangle(this.x, this.y, width, height); + this.type = Phaser.GeomSprite.RECTANGLE; + this.frameBounds.copyFrom(this.rect); + return this; + }; + GeomSprite.prototype.createPolygon = /** + * Create a polygon object + * @param width {Number} Width of the rectangle + * @param height {Number} Height of the rectangle + * @return {GeomSprite} GeomSprite instance. + */ + function (points) { + if (typeof points === "undefined") { points = []; } + this.refresh(); + this.polygon = new Phaser.Polygon(new Vector2(this.x, this.y), points); + this.type = Phaser.GeomSprite.POLYGON; + //this.frameBounds.copyFrom(this.rect); + return this; + }; + GeomSprite.prototype.refresh = /** + * Destroy all geom shapes of this sprite. + */ + function () { + this.circle = null; + this.line = null; + this.point = null; + this.rect = null; + }; + GeomSprite.prototype.update = /** + * Update bounds. + */ + function () { + // Update bounds and position? + if(this.type == Phaser.GeomSprite.UNASSIGNED) { + return; + } else if(this.type == Phaser.GeomSprite.CIRCLE) { + this.circle.x = this.x; + this.circle.y = this.y; + this.frameBounds.width = this.circle.diameter; + this.frameBounds.height = this.circle.diameter; + } else if(this.type == Phaser.GeomSprite.LINE) { + this.line.x1 = this.x; + this.line.y1 = this.y; + this.frameBounds.setTo(this.x, this.y, this.line.width, this.line.height); + } else if(this.type == Phaser.GeomSprite.POINT) { + this.point.x = this.x; + this.point.y = this.y; + } else if(this.type == Phaser.GeomSprite.RECTANGLE) { + this.rect.x = this.x; + this.rect.y = this.y; + this.frameBounds.copyFrom(this.rect); + } + }; + GeomSprite.prototype.inCamera = /** + * Check whether this object is visible in a specific camera rectangle. + * @param camera {Rectangle} The rectangle you want to check. + * @return {boolean} Return true if bounds of this sprite intersects the given rectangle, otherwise return false. + */ + function (camera) { + if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { + this._dx = this.frameBounds.x - (camera.x * this.scrollFactor.x); + this._dy = this.frameBounds.y - (camera.y * this.scrollFactor.x); + this._dw = this.frameBounds.width * this.scale.x; + this._dh = this.frameBounds.height * this.scale.y; + return (camera.right > this._dx) && (camera.x < this._dx + this._dw) && (camera.bottom > this._dy) && (camera.y < this._dy + this._dh); + } else { + return camera.intersects(this.frameBounds); + } + }; + GeomSprite.prototype.render = /** + * Render this sprite to specific camera. Called by game loop after update(). + * @param camera {Camera} Camera this sprite will be rendered to. + * @cameraOffsetX {number} X offset to the camera. + * @cameraOffsetY {number} Y offset to the camera. + * @return {boolean} Return false if not rendered, otherwise return true. + */ + function (camera, cameraOffsetX, cameraOffsetY) { + // Render checks + if(this.type == Phaser.GeomSprite.UNASSIGNED || this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false) { + return false; + } + // Alpha + if(this.alpha !== 1) { + var globalAlpha = this.context.globalAlpha; + this.context.globalAlpha = this.alpha; + } + this._dx = cameraOffsetX + (this.frameBounds.x - camera.worldView.x); + this._dy = cameraOffsetY + (this.frameBounds.y - camera.worldView.y); + this._dw = this.frameBounds.width * this.scale.x; + this._dh = this.frameBounds.height * this.scale.y; + // Apply camera difference + if(this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) { + this._dx -= (camera.worldView.x * this.scrollFactor.x); + this._dy -= (camera.worldView.y * this.scrollFactor.y); + } + // Rotation is disabled for now as I don't want it to be misleading re: collision + /* + if (this.angle !== 0) + { + this.context.save(); + this.context.translate(this._dx + (this._dw / 2) - this.origin.x, this._dy + (this._dh / 2) - this.origin.y); + this.context.rotate(this.angle * (Math.PI / 180)); + this._dx = -(this._dw / 2); + this._dy = -(this._dh / 2); + } + */ + this._dx = 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 == Phaser.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 == Phaser.GeomSprite.LINE) { + this.context.beginPath(); + this.context.moveTo(this._dx, this._dy); + this.context.lineTo(this.line.x2, this.line.y2); + this.context.stroke(); + this.context.closePath(); + } else if(this.type == Phaser.GeomSprite.POINT) { + this.context.fillRect(this._dx, this._dy, 2, 2); + } else if(this.type == Phaser.GeomSprite.RECTANGLE) { + // We can use the faster fillRect if we don't need the outline + if(this.renderOutline == false) { + this.context.fillRect(this._dx, this._dy, this.rect.width, this.rect.height); + } else { + this.context.beginPath(); + this.context.rect(this._dx, this._dy, this.rect.width, this.rect.height); + this.context.stroke(); + if(this.renderFill) { + this.context.fill(); + } + this.context.closePath(); + } + // And now the edge points + this.context.fillStyle = 'rgb(255,255,255)'; + //this.renderPoint(this.rect.topLeft, this._dx, this._dy, 2); + //this.renderPoint(this.rect.topCenter, this._dx, this._dy, 2); + //this.renderPoint(this.rect.topRight, this._dx, this._dy, 2); + //this.renderPoint(this.rect.leftCenter, this._dx, this._dy, 2); + //this.renderPoint(this.rect.center, this._dx, this._dy, 2); + //this.renderPoint(this.rect.rightCenter, this._dx, this._dy, 2); + //this.renderPoint(this.rect.bottomLeft, this._dx, this._dy, 2); + //this.renderPoint(this.rect.bottomCenter, this._dx, this._dy, 2); + //this.renderPoint(this.rect.bottomRight, this._dx, this._dy, 2); + this.renderPoint(this.rect.topLeft, 0, 0, 2); + this.renderPoint(this.rect.topCenter, 0, 0, 2); + this.renderPoint(this.rect.topRight, 0, 0, 2); + this.renderPoint(this.rect.leftCenter, 0, 0, 2); + this.renderPoint(this.rect.center, 0, 0, 2); + this.renderPoint(this.rect.rightCenter, 0, 0, 2); + this.renderPoint(this.rect.bottomLeft, 0, 0, 2); + this.renderPoint(this.rect.bottomCenter, 0, 0, 2); + this.renderPoint(this.rect.bottomRight, 0, 0, 2); + } + this._game.stage.restoreCanvasValues(); + if(this.rotation !== 0) { + this.context.translate(0, 0); + this.context.restore(); + } + if(globalAlpha > -1) { + this.context.globalAlpha = globalAlpha; + } + return true; + }; + GeomSprite.prototype.renderPoint = /** + * Render a point of geometry. + * @param point {Point} Position of the point. + * @param offsetX {number} X offset to its position. + * @param offsetY {number} Y offset to its position. + * @param [size] {number} point size. + */ + function (point, offsetX, offsetY, size) { + if (typeof offsetX === "undefined") { offsetX = 0; } + if (typeof offsetY === "undefined") { offsetY = 0; } + if (typeof size === "undefined") { size = 1; } + this.context.fillRect(offsetX + point.x, offsetY + point.y, size, size); + }; + GeomSprite.prototype.renderDebugInfo = /** + * Render debug infos. (this method does not work now) + * @param x {number} X position of the debug info to be rendered. + * @param y {number} Y position of the debug info to be rendered. + * @param [color] {number} color of the debug info to be rendered. (format is css color string) + */ + function (x, y, color) { + if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } + //this.context.fillStyle = color; + //this.context.fillText('Sprite: ' + this.name + ' (' + this.frameBounds.width + ' x ' + this.frameBounds.height + ')', x, y); + //this.context.fillText('x: ' + this.frameBounds.x.toFixed(1) + ' y: ' + this.frameBounds.y.toFixed(1) + ' rotation: ' + this.angle.toFixed(1), x, y + 14); + //this.context.fillText('dx: ' + this._dx.toFixed(1) + ' dy: ' + this._dy.toFixed(1) + ' dw: ' + this._dw.toFixed(1) + ' dh: ' + this._dh.toFixed(1), x, y + 28); + //this.context.fillText('sx: ' + this._sx.toFixed(1) + ' sy: ' + this._sy.toFixed(1) + ' sw: ' + this._sw.toFixed(1) + ' sh: ' + this._sh.toFixed(1), x, y + 42); + }; + GeomSprite.prototype.collide = /** + * Gives a basic boolean response to a geometric collision. + * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. + * @param source {GeomSprite} Sprite you want to check. + * @return {boolean} Whether they overlaps or not. + */ + function (source) { + // Circle vs. Circle + if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.CIRCLE) { + return Phaser.Collision.circleToCircle(this.circle, source.circle).result; + } + // Circle vs. Rect + if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.RECTANGLE) { + return Phaser.Collision.circleToRectangle(this.circle, source.rect).result; + } + // Circle vs. Point + if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.POINT) { + return Phaser.Collision.circleContainsPoint(this.circle, source.point).result; + } + // Circle vs. Line + if(this.type == Phaser.GeomSprite.CIRCLE && source.type == Phaser.GeomSprite.LINE) { + return Phaser.Collision.lineToCircle(source.line, this.circle).result; + } + // Rect vs. Rect + if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.RECTANGLE) { + return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result; + } + // Rect vs. Circle + if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.CIRCLE) { + return Phaser.Collision.circleToRectangle(source.circle, this.rect).result; + } + // Rect vs. Point + if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.POINT) { + return Phaser.Collision.pointToRectangle(source.point, this.rect).result; + } + // Rect vs. Line + if(this.type == Phaser.GeomSprite.RECTANGLE && source.type == Phaser.GeomSprite.LINE) { + return Phaser.Collision.lineToRectangle(source.line, this.rect).result; + } + // Point vs. Point + if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.POINT) { + return this.point.equals(source.point); + } + // Point vs. Circle + if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.CIRCLE) { + return Phaser.Collision.circleContainsPoint(source.circle, this.point).result; + } + // Point vs. Rect + if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.RECTANGLE) { + return Phaser.Collision.pointToRectangle(this.point, source.rect).result; + } + // Point vs. Line + if(this.type == Phaser.GeomSprite.POINT && source.type == Phaser.GeomSprite.LINE) { + return source.line.isPointOnLine(this.point.x, this.point.y); + } + // Line vs. Line + if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.LINE) { + return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result; + } + // Line vs. Circle + if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.CIRCLE) { + return Phaser.Collision.lineToCircle(this.line, source.circle).result; + } + // Line vs. Rect + if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.RECTANGLE) { + return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result; + } + // Line vs. Point + if(this.type == Phaser.GeomSprite.LINE && source.type == Phaser.GeomSprite.POINT) { + return this.line.isPointOnLine(source.point.x, source.point.y); + } + return false; + }; + return GeomSprite; + })(Phaser.GameObject); + Phaser.GeomSprite = GeomSprite; +})(Phaser || (Phaser = {})); diff --git a/Phaser/gameobjects/Particle.js b/Phaser/gameobjects/Particle.js new file mode 100644 index 00000000..fbb95484 --- /dev/null +++ b/Phaser/gameobjects/Particle.js @@ -0,0 +1,74 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/** +* Phaser - Particle +* +* This is a simple particle class that extends a Sprite to have a slightly more +* specialised behaviour. It is used exclusively by the Emitter class and can be extended as required. +*/ +var Phaser; +(function (Phaser) { + var Particle = (function (_super) { + __extends(Particle, _super); + /** + * Instantiate a new particle. Like Sprite, all meaningful creation + * happens during loadGraphic() or makeGraphic() or whatever. + */ + function Particle(game) { + _super.call(this, game); + this.lifespan = 0; + this.friction = 500; + } + Particle.prototype.update = /** + * The particle's main update logic. Basically it checks to see if it should + * be dead yet, and then has some special bounce behavior if there is some gravity on it. + */ + function () { + //lifespan behavior + if(this.lifespan <= 0) { + return; + } + this.lifespan -= this._game.time.elapsed; + if(this.lifespan <= 0) { + this.kill(); + } + //simpler bounce/spin behavior for now + if(this.touching) { + if(this.angularVelocity != 0) { + this.angularVelocity = -this.angularVelocity; + } + } + if(this.acceleration.y > 0)//special behavior for particles with gravity + { + if(this.touching & Phaser.Collision.FLOOR) { + this.drag.x = this.friction; + if(!(this.wasTouching & Phaser.Collision.FLOOR)) { + if(this.velocity.y < -this.elasticity * 10) { + if(this.angularVelocity != 0) { + this.angularVelocity *= -this.elasticity; + } + } else { + this.velocity.y = 0; + this.angularVelocity = 0; + } + } + } else { + this.drag.x = 0; + } + } + }; + Particle.prototype.onEmit = /** + * Triggered whenever this object is launched by a Emitter. + * You can override this to add custom behavior like a sound or AI or something. + */ + function () { + }; + return Particle; + })(Phaser.Sprite); + Phaser.Particle = Particle; +})(Phaser || (Phaser = {})); diff --git a/Phaser/gameobjects/Tilemap.js b/Phaser/gameobjects/Tilemap.js new file mode 100644 index 00000000..e9e3170e --- /dev/null +++ b/Phaser/gameobjects/Tilemap.js @@ -0,0 +1,314 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/// +/// +/** +* Phaser - Tilemap +* +* This GameObject allows for the display of a tilemap within the game world. Tile maps consist of an image, tile data and a size. +* Internally it creates a TilemapLayer for each layer in the tilemap. +*/ +var Phaser; +(function (Phaser) { + var Tilemap = (function (_super) { + __extends(Tilemap, _super); + /** + * Tilemap constructor + * Create a new Tilemap. + * + * @param game {Phaser.Game} Current game instance. + * @param key {string} Asset key for this map. + * @param mapData {string} Data of this map. (a big 2d array, normally in csv) + * @param format {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. + * @param resizeWorld {boolean} Resize the world bound automatically based on this tilemap? + * @param tileWidth {number} Width of tiles in this map. + * @param tileHeight {number} Height of tiles in this map. + */ + function Tilemap(game, key, mapData, format, resizeWorld, tileWidth, tileHeight) { + if (typeof resizeWorld === "undefined") { resizeWorld = true; } + if (typeof tileWidth === "undefined") { tileWidth = 0; } + if (typeof tileHeight === "undefined") { tileHeight = 0; } + _super.call(this, game); + /** + * Tilemap collision callback. + * @type {function} + */ + this.collisionCallback = null; + this.isGroup = false; + this.tiles = []; + this.layers = []; + this.mapFormat = format; + switch(format) { + case Tilemap.FORMAT_CSV: + this.parseCSV(game.cache.getText(mapData), key, tileWidth, tileHeight); + break; + case Tilemap.FORMAT_TILED_JSON: + this.parseTiledJSON(game.cache.getText(mapData), key); + break; + } + if(this.currentLayer && resizeWorld) { + this._game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true); + } + } + Tilemap.FORMAT_CSV = 0; + Tilemap.FORMAT_TILED_JSON = 1; + Tilemap.prototype.update = /** + * Inherited update method. + */ + function () { + }; + Tilemap.prototype.render = /** + * Render this tilemap to a specific camera with specific offset. + * @param camera {Camera} The camera this tilemap will be rendered to. + * @param cameraOffsetX {number} X offset of the camera. + * @param cameraOffsetY {number} Y offset of the camera. + */ + function (camera, cameraOffsetX, cameraOffsetY) { + if(this.cameraBlacklist.indexOf(camera.ID) == -1) { + // Loop through the layers + for(var i = 0; i < this.layers.length; i++) { + this.layers[i].render(camera, cameraOffsetX, cameraOffsetY); + } + } + }; + Tilemap.prototype.parseCSV = /** + * Parset csv map data and generate tiles. + * @param data {string} CSV map data. + * @param key {string} Asset key for tileset image. + * @param tileWidth {number} Width of its tile. + * @param tileHeight {number} Height of its tile. + */ + function (data, key, tileWidth, tileHeight) { + var layer = new Phaser.TilemapLayer(this._game, this, key, Phaser.Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight); + // Trim any rogue whitespace from the data + data = data.trim(); + var rows = data.split("\n"); + for(var i = 0; i < rows.length; i++) { + var column = rows[i].split(","); + if(column.length > 0) { + layer.addColumn(column); + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.parseTiledJSON = /** + * Parset JSON map data and generate tiles. + * @param data {string} JSON map data. + * @param key {string} Asset key for tileset image. + */ + function (data, key) { + // Trim any rogue whitespace from the data + data = data.trim(); + var json = JSON.parse(data); + for(var i = 0; i < json.layers.length; i++) { + var layer = new Phaser.TilemapLayer(this._game, this, key, Phaser.Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight); + layer.alpha = json.layers[i].opacity; + layer.visible = json.layers[i].visible; + layer.tileMargin = json.tilesets[0].margin; + layer.tileSpacing = json.tilesets[0].spacing; + var c = 0; + var row; + for(var t = 0; t < json.layers[i].data.length; t++) { + if(c == 0) { + row = []; + } + row.push(json.layers[i].data[t]); + c++; + if(c == json.layers[i].width) { + layer.addColumn(row); + c = 0; + } + } + layer.updateBounds(); + var tileQuantity = layer.parseTileOffsets(); + this.currentLayer = layer; + this.collisionLayer = layer; + this.layers.push(layer); + } + this.generateTiles(tileQuantity); + }; + Tilemap.prototype.generateTiles = /** + * Create tiles of given quantity. + * @param qty {number} Quentity of tiles to be generated. + */ + function (qty) { + for(var i = 0; i < qty; i++) { + this.tiles.push(new Phaser.Tile(this._game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight)); + } + }; + Object.defineProperty(Tilemap.prototype, "widthInPixels", { + get: function () { + return this.currentLayer.widthInPixels; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tilemap.prototype, "heightInPixels", { + get: function () { + return this.currentLayer.heightInPixels; + }, + enumerable: true, + configurable: true + }); + Tilemap.prototype.setCollisionCallback = // Tile Collision + /** + * Set callback to be called when this tilemap collides. + * @param context {object} Callback will be called with this context. + * @param callback {function} Callback function. + */ + function (context, callback) { + this.collisionCallbackContext = context; + this.collisionCallback = callback; + }; + Tilemap.prototype.setCollisionRange = /** + * Set collision configs of tiles in a range index. + * @param start {number} First index of tiles. + * @param end {number} Last index of tiles. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + function (start, end, collision, resetCollisions, separateX, separateY) { + if (typeof collision === "undefined") { collision = Phaser.Collision.ANY; } + if (typeof resetCollisions === "undefined") { resetCollisions = false; } + if (typeof separateX === "undefined") { separateX = true; } + if (typeof separateY === "undefined") { separateY = true; } + for(var i = start; i < end; i++) { + this.tiles[i].setCollision(collision, resetCollisions, separateX, separateY); + } + }; + Tilemap.prototype.setCollisionByIndex = /** + * Set collision configs of tiles with given index. + * @param values {number[]} Index array which contains all tile indexes. The tiles with those indexes will be setup with rest parameters. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + function (values, collision, resetCollisions, separateX, separateY) { + if (typeof collision === "undefined") { collision = Phaser.Collision.ANY; } + if (typeof resetCollisions === "undefined") { resetCollisions = false; } + if (typeof separateX === "undefined") { separateX = true; } + if (typeof separateY === "undefined") { separateY = true; } + for(var i = 0; i < values.length; i++) { + this.tiles[values[i]].setCollision(collision, resetCollisions, separateX, separateY); + } + }; + Tilemap.prototype.getTileByIndex = // Tile Management + /** + * Get the tile by its index. + * @param value {number} Index of the tile you want to get. + * @return {Tile} The tile with given index. + */ + function (value) { + if(this.tiles[value]) { + return this.tiles[value]; + } + return null; + }; + Tilemap.prototype.getTile = /** + * Get the tile located at specific position and layer. + * @param x {number} X position of this tile located. + * @param y {number} Y position of this tile located. + * @param [layer] {number} layer of this tile located. + * @return {Tile} The tile with specific properties. + */ + function (x, y, layer) { + if (typeof layer === "undefined") { layer = 0; } + return this.tiles[this.layers[layer].getTileIndex(x, y)]; + }; + Tilemap.prototype.getTileFromWorldXY = /** + * Get the tile located at specific position (in world coordinate) and layer. (thus you give a position of a point which is within the tile) + * @param x {number} X position of the point in target tile. + * @param x {number} Y position of the point in target tile. + * @param [layer] {number} layer of this tile located. + * @return {Tile} The tile with specific properties. + */ + function (x, y, layer) { + if (typeof layer === "undefined") { layer = 0; } + return this.tiles[this.layers[layer].getTileFromWorldXY(x, y)]; + }; + Tilemap.prototype.getTileFromInputXY = function (layer) { + if (typeof layer === "undefined") { layer = 0; } + return this.tiles[this.layers[layer].getTileFromWorldXY(this._game.input.getWorldX(), this._game.input.getWorldY())]; + }; + Tilemap.prototype.getTileOverlaps = /** + * Get tiles overlaps the given object. + * @param object {GameObject} Tiles you want to get that overlaps this. + * @return {array} Array with tiles informations. (Each contains x, y and the tile.) + */ + function (object) { + return this.currentLayer.getTileOverlaps(object); + }; + Tilemap.prototype.collide = // COLLIDE + /** + * Check whether this tilemap collides with the given game object or group of objects. + * @param objectOrGroup {function} Target object of group you want to check. + * @param callback {function} This is called if objectOrGroup collides the tilemap. + * @param context {object} Callback will be called with this context. + * @return {boolean} Return true if this collides with given object, otherwise return false. + */ + function (objectOrGroup, callback, context) { + if (typeof objectOrGroup === "undefined") { objectOrGroup = null; } + if (typeof callback === "undefined") { callback = null; } + if (typeof context === "undefined") { context = null; } + if(callback !== null && context !== null) { + this.collisionCallback = callback; + this.collisionCallbackContext = context; + } + if(objectOrGroup == null) { + objectOrGroup = this._game.world.group; + } + // Group? + if(objectOrGroup.isGroup == false) { + this.collideGameObject(objectOrGroup); + } else { + objectOrGroup.forEachAlive(this, this.collideGameObject, true); + } + }; + Tilemap.prototype.collideGameObject = /** + * Check whether this tilemap collides with the given game object. + * @param object {GameObject} Target object you want to check. + * @return {boolean} Return true if this collides with given object, otherwise return false. + */ + function (object) { + if(object !== this && object.immovable == false && object.exists == true && object.allowCollisions != Phaser.Collision.NONE) { + this._tempCollisionData = this.collisionLayer.getTileOverlaps(object); + if(this.collisionCallback !== null && this._tempCollisionData.length > 0) { + this.collisionCallback.call(this.collisionCallbackContext, object, this._tempCollisionData); + } + return true; + } else { + return false; + } + }; + Tilemap.prototype.putTile = /** + * Set a tile to a specific layer. + * @param x {number} X position of this tile. + * @param y {number} Y position of this tile. + * @param index {number} The index of this tile type in the core map data. + * @param [layer] {number} which layer you want to set the tile to. + */ + function (x, y, index, layer) { + if (typeof layer === "undefined") { layer = 0; } + this.layers[layer].putTile(x, y, index); + }; + return Tilemap; + })(Phaser.GameObject); + Phaser.Tilemap = Tilemap; + // Set current layer + // Set layer order? + // Delete tiles of certain type + // Erase tiles + })(Phaser || (Phaser = {})); diff --git a/Phaser/geom/IntersectResult.js b/Phaser/geom/IntersectResult.js new file mode 100644 index 00000000..f9e2e865 --- /dev/null +++ b/Phaser/geom/IntersectResult.js @@ -0,0 +1,45 @@ +/// +/** +* Phaser - IntersectResult +* +* A light-weight result object to hold the results of an intersection. For when you need more than just true/false. +*/ +var Phaser; +(function (Phaser) { + var IntersectResult = (function () { + function IntersectResult() { + /** + * Did they intersect or not? + * @property result + * @type {Boolean} + */ + this.result = false; + } + IntersectResult.prototype.setTo = /** + * + * @method setTo + * @param {Number} x1 + * @param {Number} y1 + * @param {Number} [x2] + * @param {Number} [y2] + * @param {Number} [width] + * @param {Number} [height] + */ + function (x1, y1, x2, y2, width, height) { + if (typeof x2 === "undefined") { x2 = 0; } + if (typeof y2 === "undefined") { y2 = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + this.x = x1; + this.y = y1; + this.x1 = x1; + this.y1 = y1; + this.x2 = x2; + this.y2 = y2; + this.width = width; + this.height = height; + }; + return IntersectResult; + })(); + Phaser.IntersectResult = IntersectResult; +})(Phaser || (Phaser = {})); diff --git a/Phaser/geom/MicroPoint.js b/Phaser/geom/MicroPoint.js new file mode 100644 index 00000000..750bd2fd --- /dev/null +++ b/Phaser/geom/MicroPoint.js @@ -0,0 +1,134 @@ +/// +/** +* Phaser - MicroPoint +* +* The MicroPoint object represents a location in a two-dimensional coordinate system, +* where x represents the horizontal axis and y represents the vertical axis. +* It is different to the Point class in that it doesn't contain any of the help methods like add/substract/distanceTo, etc. +* Use a MicroPoint when all you literally need is a solid container for x and y (such as in the Rectangle class). +*/ +var Phaser; +(function (Phaser) { + var MicroPoint = (function () { + /** + * Creates a new point. If you pass no parameters to this method, a point is created at (0,0). + * @class MicroPoint + * @constructor + * @param {Number} x The horizontal position of this point (default 0) + * @param {Number} y The vertical position of this point (default 0) + **/ + function MicroPoint(x, y, parent) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof parent === "undefined") { parent = null; } + this._x = x; + this._y = y; + this.parent = parent; + } + Object.defineProperty(MicroPoint.prototype, "x", { + get: /** + * The x coordinate of the top-left corner of the rectangle + * @property x + * @type Number + **/ + function () { + return this._x; + }, + set: /** + * The x coordinate of the top-left corner of the rectangle + * @property x + * @type Number + **/ + function (value) { + this._x = value; + if(this.parent) { + this.parent.updateBounds(); + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(MicroPoint.prototype, "y", { + get: /** + * The y coordinate of the top-left corner of the rectangle + * @property y + * @type Number + **/ + function () { + return this._y; + }, + set: /** + * The y coordinate of the top-left corner of the rectangle + * @property y + * @type Number + **/ + function (value) { + this._y = value; + if(this.parent) { + this.parent.updateBounds(); + } + }, + enumerable: true, + configurable: true + }); + MicroPoint.prototype.copyFrom = /** + * Copies the x and y values from any given object to this MicroPoint. + * @method copyFrom + * @param {any} source - The object to copy from. + * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. + **/ + function (source) { + return this.setTo(source.x, source.y); + }; + MicroPoint.prototype.copyTo = /** + * Copies the x and y values from this MicroPoint to any given object. + * @method copyTo + * @param {any} target - The object to copy to. + * @return {any} The target object. + **/ + function (target) { + target.x = this._x; + target.y = this._y; + return target; + }; + MicroPoint.prototype.setTo = /** + * Sets the x and y values of this MicroPoint object to the given coordinates. + * @method setTo + * @param {Number} x - The horizontal position of this point. + * @param {Number} y - The vertical position of this point. + * @return {MicroPoint} This MicroPoint object. Useful for chaining method calls. + **/ + function (x, y, callParent) { + if (typeof callParent === "undefined") { callParent = true; } + this._x = x; + this._y = y; + if(this.parent != null && callParent == true) { + this.parent.updateBounds(); + } + return this; + }; + MicroPoint.prototype.equals = /** + * Determines whether this MicroPoint object and the given object are equal. They are equal if they have the same x and y values. + * @method equals + * @param {any} point - The object to compare against. Must have x and y properties. + * @return {Boolean} A value of true if the object is equal to this MicroPoin object; false if it is not equal. + **/ + function (toCompare) { + if(this._x === toCompare.x && this._y === toCompare.y) { + return true; + } else { + return false; + } + }; + MicroPoint.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return '[{MicroPoint (x=' + this._x + ' y=' + this._y + ')}]'; + }; + return MicroPoint; + })(); + Phaser.MicroPoint = MicroPoint; +})(Phaser || (Phaser = {})); diff --git a/Phaser/geom/Polygon.js b/Phaser/geom/Polygon.js new file mode 100644 index 00000000..f4e64851 --- /dev/null +++ b/Phaser/geom/Polygon.js @@ -0,0 +1,47 @@ +/// +/** +* Phaser - Polygon +* +*/ +var Phaser; +(function (Phaser) { + var Polygon = (function () { + /** + * A *convex* clockwise polygon + * @class Polygon + * @constructor + * @param {Vector2} pos A vector representing the origin of the polygon (all other points are relative to this one) + * @param {Array.} points An Array of vectors representing the points in the polygon, in clockwise order. + **/ + function Polygon(pos, points, parent) { + if (typeof pos === "undefined") { pos = new Vector2(); } + if (typeof points === "undefined") { points = []; } + if (typeof parent === "undefined") { parent = null; } + this.pos = pos; + this.points = points; + this.parent = parent; + this.recalc(); + } + Polygon.prototype.recalc = /** + * Recalculate the edges and normals of the polygon. This + * MUST be called if the points array is modified at all and + * the edges or normals are to be accessed. + */ + function () { + var points = this.points; + var len = points.length; + this.edges = []; + this.normals = []; + for(var i = 0; i < len; i++) { + var p1 = points[i]; + var p2 = i < len - 1 ? points[i + 1] : points[0]; + var e = new Vector2().copyFrom(p2).sub(p1); + var n = new Vector2().copyFrom(e).perp().normalize(); + this.edges.push(e); + this.normals.push(n); + } + }; + return Polygon; + })(); + Phaser.Polygon = Polygon; +})(Phaser || (Phaser = {})); diff --git a/Phaser/geom/Quad.js b/Phaser/geom/Quad.js new file mode 100644 index 00000000..dde8e8cc --- /dev/null +++ b/Phaser/geom/Quad.js @@ -0,0 +1,109 @@ +/// +/** +* Phaser - Quad +* +* A Quad object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height. +* Very much like a Rectangle only without all of the additional methods and properties of that class. +*/ +var Phaser; +(function (Phaser) { + var Quad = (function () { + /** + * Creates a new Quad object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. + * @class Quad + * @constructor + * @param {Number} x The x coordinate of the top-left corner of the quad. + * @param {Number} y The y coordinate of the top-left corner of the quad. + * @param {Number} width The width of the quad. + * @param {Number} height The height of the quad. + * @return {Quad } This object + **/ + function Quad(x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + this.setTo(x, y, width, height); + } + Quad.prototype.setTo = /** + * Sets the Quad to the specified size. + * @method setTo + * @param {Number} x The x coordinate of the top-left corner of the quad. + * @param {Number} y The y coordinate of the top-left corner of the quad. + * @param {Number} width The width of the quad. + * @param {Number} height The height of the quad. + * @return {Quad} This object + **/ + function (x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }; + Object.defineProperty(Quad.prototype, "left", { + get: function () { + return this.x; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Quad.prototype, "right", { + get: function () { + return this.x + this.width; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Quad.prototype, "top", { + get: function () { + return this.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Quad.prototype, "bottom", { + get: function () { + return this.y + this.height; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Quad.prototype, "halfWidth", { + get: function () { + return this.width / 2; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Quad.prototype, "halfHeight", { + get: function () { + return this.height / 2; + }, + enumerable: true, + configurable: true + }); + Quad.prototype.intersects = /** + * Determines whether the object specified intersects (overlaps) with this Quad object. + * This method checks the x, y, width, and height properties of the specified Quad object to see if it intersects with this Quad object. + * @method intersects + * @param {Object} q The object to check for intersection with this Quad. Must have left/right/top/bottom properties (Rectangle, Quad). + * @param {Number} t A tolerance value to allow for an intersection test with padding, default to 0 + * @return {Boolean} A value of true if the specified object intersects with this Quad; otherwise false. + **/ + function (q, t) { + if (typeof t === "undefined") { t = 0; } + return !(q.left > this.right + t || q.right < this.left - t || q.top > this.bottom + t || q.bottom < this.top - t); + }; + Quad.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + function () { + return "[{Quad (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]"; + }; + return Quad; + })(); + Phaser.Quad = Quad; +})(Phaser || (Phaser = {})); diff --git a/Phaser/geom/Response.js b/Phaser/geom/Response.js new file mode 100644 index 00000000..9b363716 --- /dev/null +++ b/Phaser/geom/Response.js @@ -0,0 +1,41 @@ +/// +/// +/** +* Phaser - Response +* +*/ +var Phaser; +(function (Phaser) { + var Response = (function () { + /** + * An object representing the result of an intersection. Contain information about: + * - The two objects participating in the intersection + * - The vector representing the minimum change necessary to extract the first object + * from the second one. + * - Whether the first object is entirely inside the second, or vice versa. + * + * @constructor + */ + function Response() { + this.a = null; + this.b = null; + this.overlapN = new Vector2(); + this.overlapV = new Vector2(); + this.clear(); + } + Response.prototype.clear = /** + * Set some values of the response back to their defaults. Call this between tests if + * you are going to reuse a single Response object for multiple intersection tests (recommented) + * + * @return {Response} This for chaining + */ + function () { + this.aInB = true; + this.bInA = true; + this.overlap = Number.MAX_VALUE; + return this; + }; + return Response; + })(); + Phaser.Response = Response; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/Camera.js b/Phaser/system/Camera.js new file mode 100644 index 00000000..5079f829 --- /dev/null +++ b/Phaser/system/Camera.js @@ -0,0 +1,353 @@ +/// +/// +/** +* Phaser - Camera +* +* A Camera is your view into the game world. It has a position, size, scale and rotation and renders only those objects +* within its field of view. The game automatically creates a single Stage sized camera on boot, but it can be changed and +* additional cameras created via the CameraManager. +*/ +var Phaser; +(function (Phaser) { + var Camera = (function () { + /** + * Instantiates a new camera at the specified location, with the specified size and zoom level. + * + * @param X X location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param Y Y location of the camera's display in pixels. Uses native, 1:1 resolution, ignores zoom. + * @param Width The width of the camera display in pixels. + * @param Height The height of the camera display in pixels. + * @param Zoom The initial zoom level of the camera. A zoom level of 2 will make all pixels display at 2x resolution. + */ + function Camera(game, id, x, y, width, height) { + this._clip = false; + this._rotation = 0; + this._target = null; + this._sx = 0; + this._sy = 0; + this.scale = new Phaser.MicroPoint(1, 1); + this.scroll = new Phaser.MicroPoint(0, 0); + this.bounds = null; + this.deadzone = null; + // Camera Border + this.disableClipping = false; + this.showBorder = false; + this.borderColor = 'rgb(255,255,255)'; + // Camera Background Color + this.opaque = true; + this._bgColor = 'rgb(0,0,0)'; + this._bgTextureRepeat = 'repeat'; + // Camera Shadow + this.showShadow = false; + this.shadowColor = 'rgb(0,0,0)'; + this.shadowBlur = 10; + this.shadowOffset = new Phaser.MicroPoint(4, 4); + this.visible = true; + this.alpha = 1; + // The x/y position of the current input event in world coordinates + this.inputX = 0; + this.inputY = 0; + this._game = game; + this.ID = id; + this._stageX = x; + this._stageY = y; + this.fx = new Phaser.FXManager(this._game, this); + // The view into the world canvas we wish to render + this.worldView = new Phaser.Rectangle(0, 0, width, height); + this.checkClip(); + } + Camera.STYLE_LOCKON = 0; + Camera.STYLE_PLATFORMER = 1; + Camera.STYLE_TOPDOWN = 2; + Camera.STYLE_TOPDOWN_TIGHT = 3; + Camera.prototype.follow = function (target, style) { + if (typeof style === "undefined") { style = Camera.STYLE_LOCKON; } + this._target = target; + var helper; + switch(style) { + case Camera.STYLE_PLATFORMER: + var w = this.width / 8; + var h = this.height / 3; + this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); + break; + case Camera.STYLE_TOPDOWN: + helper = Math.max(this.width, this.height) / 4; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + case Camera.STYLE_TOPDOWN_TIGHT: + helper = Math.max(this.width, this.height) / 8; + this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); + break; + case Camera.STYLE_LOCKON: + default: + this.deadzone = null; + break; + } + }; + Camera.prototype.focusOnXY = function (x, y) { + x += (x > 0) ? 0.0000001 : -0.0000001; + y += (y > 0) ? 0.0000001 : -0.0000001; + this.scroll.x = Math.round(x - this.worldView.halfWidth); + this.scroll.y = Math.round(y - this.worldView.halfHeight); + }; + Camera.prototype.focusOn = function (point) { + point.x += (point.x > 0) ? 0.0000001 : -0.0000001; + point.y += (point.y > 0) ? 0.0000001 : -0.0000001; + this.scroll.x = Math.round(point.x - this.worldView.halfWidth); + this.scroll.y = Math.round(point.y - this.worldView.halfHeight); + }; + Camera.prototype.setBounds = /** + * Specify the boundaries of the world or where the camera is allowed to move. + * + * @param x The smallest X value of your world (usually 0). + * @param y The smallest Y value of your world (usually 0). + * @param width The largest X value of your world (usually the world width). + * @param height The largest Y value of your world (usually the world height). + */ + function (x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = 0; } + if (typeof height === "undefined") { height = 0; } + if(this.bounds == null) { + this.bounds = new Phaser.Rectangle(); + } + this.bounds.setTo(x, y, width, height); + this.scroll.setTo(0, 0); + this.update(); + }; + Camera.prototype.update = function () { + this.fx.preUpdate(); + if(this._target !== null) { + if(this.deadzone == null) { + this.focusOnXY(this._target.x + this._target.origin.x, this._target.y + this._target.origin.y); + } else { + var edge; + var targetX = this._target.x + ((this._target.x > 0) ? 0.0000001 : -0.0000001); + var targetY = this._target.y + ((this._target.y > 0) ? 0.0000001 : -0.0000001); + edge = targetX - this.deadzone.x; + if(this.scroll.x > edge) { + this.scroll.x = edge; + } + edge = targetX + this._target.width - this.deadzone.x - this.deadzone.width; + if(this.scroll.x < edge) { + this.scroll.x = edge; + } + edge = targetY - this.deadzone.y; + if(this.scroll.y > edge) { + this.scroll.y = edge; + } + edge = targetY + this._target.height - this.deadzone.y - this.deadzone.height; + if(this.scroll.y < edge) { + this.scroll.y = edge; + } + } + } + // Make sure we didn't go outside the cameras bounds + if(this.bounds !== null) { + if(this.scroll.x < this.bounds.left) { + this.scroll.x = this.bounds.left; + } + if(this.scroll.x > this.bounds.right - this.width) { + this.scroll.x = (this.bounds.right - this.width) + 1; + } + if(this.scroll.y < this.bounds.top) { + this.scroll.y = this.bounds.top; + } + if(this.scroll.y > this.bounds.bottom - this.height) { + this.scroll.y = (this.bounds.bottom - this.height) + 1; + } + } + this.worldView.x = this.scroll.x; + this.worldView.y = this.scroll.y; + // Input values + this.inputX = this.worldView.x + this._game.input.x; + this.inputY = this.worldView.y + this._game.input.y; + this.fx.postUpdate(); + }; + Camera.prototype.render = function () { + if(this.visible === false || this.alpha < 0.1) { + return; + } + //if (this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) + //{ + //this._game.stage.context.save(); + //} + // It may be safer/quicker to just save the context every frame regardless (needs testing on mobile) + this._game.stage.context.save(); + this.fx.preRender(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); + if(this.alpha !== 1) { + this._game.stage.context.globalAlpha = this.alpha; + } + this._sx = this._stageX; + this._sy = this._stageY; + // Shadow + if(this.showShadow) { + this._game.stage.context.shadowColor = this.shadowColor; + this._game.stage.context.shadowBlur = this.shadowBlur; + this._game.stage.context.shadowOffsetX = this.shadowOffset.x; + this._game.stage.context.shadowOffsetY = this.shadowOffset.y; + } + // Scale on + if(this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.scale(this.scale.x, this.scale.y); + this._sx = this._sx / this.scale.x; + this._sy = this._sy / this.scale.y; + } + // Rotation - translate to the mid-point of the camera + if(this._rotation !== 0) { + this._game.stage.context.translate(this._sx + this.worldView.halfWidth, this._sy + this.worldView.halfHeight); + this._game.stage.context.rotate(this._rotation * (Math.PI / 180)); + // now shift back to where that should actually render + this._game.stage.context.translate(-(this._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight)); + } + // Background + if(this.opaque == true) { + if(this._bgTexture) { + this._game.stage.context.fillStyle = this._bgTexture; + this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height); + } else { + this._game.stage.context.fillStyle = this._bgColor; + this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height); + } + } + // Shadow off + if(this.showShadow) { + this._game.stage.context.shadowBlur = 0; + this._game.stage.context.shadowOffsetX = 0; + this._game.stage.context.shadowOffsetY = 0; + } + this.fx.render(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height); + // Clip the camera so we don't get sprites appearing outside the edges + if(this._clip && this.disableClipping == false) { + this._game.stage.context.beginPath(); + this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); + this._game.stage.context.closePath(); + this._game.stage.context.clip(); + } + this._game.world.group.render(this, this._sx, this._sy); + if(this.showBorder) { + this._game.stage.context.strokeStyle = this.borderColor; + this._game.stage.context.lineWidth = 1; + this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); + this._game.stage.context.stroke(); + } + // Scale off + if(this.scale.x !== 1 || this.scale.y !== 1) { + this._game.stage.context.scale(1, 1); + } + this.fx.postRender(this, this._sx, this._sy, this.worldView.width, this.worldView.height); + if(this._rotation !== 0 || (this._clip && this.disableClipping == false)) { + this._game.stage.context.translate(0, 0); + } + this._game.stage.context.restore(); + if(this.alpha !== 1) { + this._game.stage.context.globalAlpha = 1; + } + }; + Object.defineProperty(Camera.prototype, "backgroundColor", { + get: function () { + return this._bgColor; + }, + set: function (color) { + this._bgColor = color; + }, + enumerable: true, + configurable: true + }); + Camera.prototype.setTexture = function (key, repeat) { + if (typeof repeat === "undefined") { repeat = 'repeat'; } + this._bgTexture = this._game.stage.context.createPattern(this._game.cache.getImage(key), repeat); + this._bgTextureRepeat = repeat; + }; + Camera.prototype.setPosition = function (x, y) { + this._stageX = x; + this._stageY = y; + this.checkClip(); + }; + Camera.prototype.setSize = function (width, height) { + this.worldView.width = width; + this.worldView.height = height; + this.checkClip(); + }; + Camera.prototype.renderDebugInfo = function (x, y, color) { + if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } + this._game.stage.context.fillStyle = color; + this._game.stage.context.fillText('Camera ID: ' + this.ID + ' (' + this.worldView.width + ' x ' + this.worldView.height + ')', x, y); + this._game.stage.context.fillText('X: ' + this._stageX + ' Y: ' + this._stageY + ' Rotation: ' + this._rotation, x, y + 14); + this._game.stage.context.fillText('World X: ' + this.scroll.x.toFixed(1) + ' World Y: ' + this.scroll.y.toFixed(1), x, y + 28); + if(this.bounds) { + this._game.stage.context.fillText('Bounds: ' + this.bounds.width + ' x ' + this.bounds.height, x, y + 56); + } + }; + Object.defineProperty(Camera.prototype, "x", { + get: function () { + return this._stageX; + }, + set: function (value) { + this._stageX = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "y", { + get: function () { + return this._stageY; + }, + set: function (value) { + this._stageY = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "width", { + get: function () { + return this.worldView.width; + }, + set: function (value) { + if(value > this._game.stage.width) { + value = this._game.stage.width; + } + this.worldView.width = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "height", { + get: function () { + return this.worldView.height; + }, + set: function (value) { + if(value > this._game.stage.height) { + value = this._game.stage.height; + } + this.worldView.height = value; + this.checkClip(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Camera.prototype, "rotation", { + get: function () { + return this._rotation; + }, + set: function (value) { + this._rotation = this._game.math.wrap(value, 360, 0); + }, + enumerable: true, + configurable: true + }); + Camera.prototype.checkClip = function () { + if(this._stageX !== 0 || this._stageY !== 0 || this.worldView.width < this._game.stage.width || this.worldView.height < this._game.stage.height) { + this._clip = true; + } else { + this._clip = false; + } + }; + return Camera; + })(); + Phaser.Camera = Camera; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/CollisionMask.js b/Phaser/system/CollisionMask.js new file mode 100644 index 00000000..037d78c3 --- /dev/null +++ b/Phaser/system/CollisionMask.js @@ -0,0 +1,365 @@ +/// +/** +* Phaser - CollisionMask +*/ +var Phaser; +(function (Phaser) { + var CollisionMask = (function () { + /** + * CollisionMask constructor. Creates a new CollisionMask for the given GameObject. + * + * @param game {Phaser.Game} Current game instance. + * @param parent {Phaser.GameObject} The GameObject this CollisionMask belongs to. + * @param x {number} The initial x position of the CollisionMask. + * @param y {number} The initial y position of the CollisionMask. + * @param width {number} The width of the CollisionMask. + * @param height {number} The height of the CollisionMask. + */ + function CollisionMask(game, parent, x, y, width, height) { + /** + * Geom type of this sprite. (available: QUAD, POINT, CIRCLE, LINE, RECTANGLE, POLYGON) + * @type {number} + */ + this.type = 0; + this._game = game; + this._parent = parent; + // By default the CollisionMask is a quad + this.type = CollisionMask.QUAD; + this.quad = new Phaser.Quad(this._parent.x, this._parent.y, this._parent.width, this._parent.height); + this.offset = new Phaser.MicroPoint(0, 0); + this.last = new Phaser.MicroPoint(0, 0); + this._ref = this.quad; + return this; + } + CollisionMask.QUAD = 0; + CollisionMask.POINT = 1; + CollisionMask.CIRCLE = 2; + CollisionMask.LINE = 3; + CollisionMask.RECTANGLE = 4; + CollisionMask.POLYGON = 5; + CollisionMask.prototype.createCircle = /** + * Create a circle shape with specific diameter. + * @param diameter {number} Diameter of the circle. + * @return {CollisionMask} This + */ + function (diameter) { + this.type = CollisionMask.CIRCLE; + this.circle = new Phaser.Circle(this.last.x, this.last.y, diameter); + this._ref = this.circle; + return this; + }; + CollisionMask.prototype.preUpdate = /** + * Pre-update is called right before update() on each object in the game loop. + */ + function () { + this.last.x = this.x; + this.last.y = this.y; + }; + CollisionMask.prototype.update = function () { + this._ref.x = this._parent.x + this.offset.x; + this._ref.y = this._parent.y + this.offset.y; + }; + CollisionMask.prototype.render = /** + * Renders the bounding box around this Sprite and the contact points. Useful for visually debugging. + * @param camera {Camera} Camera the bound will be rendered to. + * @param cameraOffsetX {number} X offset of bound to the camera. + * @param cameraOffsetY {number} Y offset of bound to the camera. + */ + function (camera, cameraOffsetX, cameraOffsetY) { + var _dx = cameraOffsetX + (this.x - camera.worldView.x); + var _dy = cameraOffsetY + (this.y - camera.worldView.y); + this._parent.context.fillStyle = this._parent.renderDebugColor; + if(this.type == CollisionMask.QUAD) { + this._parent.context.fillRect(_dx, _dy, this.width, this.height); + } else if(this.type == CollisionMask.CIRCLE) { + this._parent.context.beginPath(); + this._parent.context.arc(_dx, _dy, this.circle.radius, 0, Math.PI * 2); + this._parent.context.fill(); + this._parent.context.closePath(); + } + }; + CollisionMask.prototype.destroy = /** + * Destroy all objects and references belonging to this CollisionMask + */ + function () { + this._game = null; + this._parent = null; + this._ref = null; + this.quad = null; + this.point = null; + this.circle = null; + this.rect = null; + this.line = null; + this.offset = null; + }; + CollisionMask.prototype.intersectsRaw = function (left, right, top, bottom) { + //if ((objBounds.x + objBounds.width > x) && (objBounds.x < x + width) && (objBounds.y + objBounds.height > y) && (objBounds.y < y + height)) + return true; + }; + CollisionMask.prototype.intersectsVector = function (vector) { + if(this.type == CollisionMask.QUAD) { + return this.quad.contains(vector.x, vector.y); + } + }; + CollisionMask.prototype.intersects = /** + * Gives a basic boolean response to a geometric collision. + * If you need the details of the collision use the Collision functions instead and inspect the IntersectResult object. + * @param source {GeomSprite} Sprite you want to check. + * @return {boolean} Whether they overlaps or not. + */ + function (source) { + // Quad vs. Quad + if(this.type == CollisionMask.QUAD && source.type == CollisionMask.QUAD) { + return this.quad.intersects(source.quad); + } + // Circle vs. Circle + if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.CIRCLE) { + return Phaser.Collision.circleToCircle(this.circle, source.circle).result; + } + // Circle vs. Rect + if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.RECTANGLE) { + return Phaser.Collision.circleToRectangle(this.circle, source.rect).result; + } + // Circle vs. Point + if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.POINT) { + return Phaser.Collision.circleContainsPoint(this.circle, source.point).result; + } + // Circle vs. Line + if(this.type == CollisionMask.CIRCLE && source.type == CollisionMask.LINE) { + return Phaser.Collision.lineToCircle(source.line, this.circle).result; + } + // Rect vs. Rect + if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.RECTANGLE) { + return Phaser.Collision.rectangleToRectangle(this.rect, source.rect).result; + } + // Rect vs. Circle + if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.CIRCLE) { + return Phaser.Collision.circleToRectangle(source.circle, this.rect).result; + } + // Rect vs. Point + if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.POINT) { + return Phaser.Collision.pointToRectangle(source.point, this.rect).result; + } + // Rect vs. Line + if(this.type == CollisionMask.RECTANGLE && source.type == CollisionMask.LINE) { + return Phaser.Collision.lineToRectangle(source.line, this.rect).result; + } + // Point vs. Point + if(this.type == CollisionMask.POINT && source.type == CollisionMask.POINT) { + return this.point.equals(source.point); + } + // Point vs. Circle + if(this.type == CollisionMask.POINT && source.type == CollisionMask.CIRCLE) { + return Phaser.Collision.circleContainsPoint(source.circle, this.point).result; + } + // Point vs. Rect + if(this.type == CollisionMask.POINT && source.type == CollisionMask.RECTANGLE) { + return Phaser.Collision.pointToRectangle(this.point, source.rect).result; + } + // Point vs. Line + if(this.type == CollisionMask.POINT && source.type == CollisionMask.LINE) { + return source.line.isPointOnLine(this.point.x, this.point.y); + } + // Line vs. Line + if(this.type == CollisionMask.LINE && source.type == CollisionMask.LINE) { + return Phaser.Collision.lineSegmentToLineSegment(this.line, source.line).result; + } + // Line vs. Circle + if(this.type == CollisionMask.LINE && source.type == CollisionMask.CIRCLE) { + return Phaser.Collision.lineToCircle(this.line, source.circle).result; + } + // Line vs. Rect + if(this.type == CollisionMask.LINE && source.type == CollisionMask.RECTANGLE) { + return Phaser.Collision.lineSegmentToRectangle(this.line, source.rect).result; + } + // Line vs. Point + if(this.type == CollisionMask.LINE && source.type == CollisionMask.POINT) { + return this.line.isPointOnLine(source.point.x, source.point.y); + } + return false; + }; + CollisionMask.prototype.checkHullIntersection = function (mask) { + if((this.hullX + this.hullWidth > mask.hullX) && (this.hullX < mask.hullX + mask.width) && (this.hullY + this.hullHeight > mask.hullY) && (this.hullY < mask.hullY + mask.hullHeight)) { + return true; + } else { + return false; + } + }; + Object.defineProperty(CollisionMask.prototype, "hullWidth", { + get: function () { + if(this.deltaX > 0) { + return this.width + this.deltaX; + } else { + return this.width - this.deltaX; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "hullHeight", { + get: function () { + if(this.deltaY > 0) { + return this.height + this.deltaY; + } else { + return this.height - this.deltaY; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "hullX", { + get: function () { + if(this.x < this.last.x) { + return this.x; + } else { + return this.last.x; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "hullY", { + get: function () { + if(this.y < this.last.y) { + return this.y; + } else { + return this.last.y; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "deltaXAbs", { + get: function () { + return (this.deltaX > 0 ? this.deltaX : -this.deltaX); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "deltaYAbs", { + get: function () { + return (this.deltaY > 0 ? this.deltaY : -this.deltaY); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "deltaX", { + get: function () { + return this.x - this.last.x; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "deltaY", { + get: function () { + return this.y - this.last.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "x", { + get: function () { + return this._ref.x; + //return this.quad.x; + }, + set: function (value) { + this._ref.x = value; + //this.quad.x = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "y", { + get: function () { + return this._ref.y; + //return this.quad.y; + }, + set: function (value) { + this._ref.y = value; + //this.quad.y = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "width", { + get: function () { + //return this.quad.width; + return this._ref.width; + }, + set: //public get rotation(): number { + // return this._angle; + //} + //public set rotation(value: number) { + // this._angle = this._game.math.wrap(value, 360, 0); + //} + //public get angle(): number { + // return this._angle; + //} + //public set angle(value: number) { + // this._angle = this._game.math.wrap(value, 360, 0); + //} + function (value) { + //this.quad.width = value; + this._ref.width = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "height", { + get: function () { + //return this.quad.height; + return this._ref.height; + }, + set: function (value) { + //this.quad.height = value; + this._ref.height = value; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "left", { + get: function () { + return this.x; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "right", { + get: function () { + return this.x + this.width; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "top", { + get: function () { + return this.y; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "bottom", { + get: function () { + return this.y + this.height; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "halfWidth", { + get: function () { + return this.width / 2; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(CollisionMask.prototype, "halfHeight", { + get: function () { + return this.height / 2; + }, + enumerable: true, + configurable: true + }); + return CollisionMask; + })(); + Phaser.CollisionMask = CollisionMask; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/LinkedList.js b/Phaser/system/LinkedList.js new file mode 100644 index 00000000..c2846f50 --- /dev/null +++ b/Phaser/system/LinkedList.js @@ -0,0 +1,30 @@ +/// +/** +* 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 = {})); diff --git a/Phaser/system/QuadTree.js b/Phaser/system/QuadTree.js new file mode 100644 index 00000000..7828f2b6 --- /dev/null +++ b/Phaser/system/QuadTree.js @@ -0,0 +1,355 @@ +var __extends = this.__extends || function (d, b) { + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +/// +/** +* Phaser - QuadTree +* +* A fairly generic quad tree structure for rapid overlap checks. QuadTree is also configured for single or dual list operation. +* You can add items either to its A list or its B list. When you do an overlap check, you can compare the A list to itself, +* or the A list against the B list. Handy for different things! +*/ +var Phaser; +(function (Phaser) { + var QuadTree = (function (_super) { + __extends(QuadTree, _super); + /** + * Instantiate a new Quad Tree node. + * + * @param {Number} x The X-coordinate of the point in space. + * @param {Number} y The Y-coordinate of the point in space. + * @param {Number} width Desired width of this node. + * @param {Number} height Desired height of this node. + * @param {Number} parent The parent branch or node. Pass null to create a root. + */ + function QuadTree(x, y, width, height, parent) { + if (typeof parent === "undefined") { parent = null; } + _super.call(this, x, y, width, height); + this._headA = this._tailA = new LinkedList(); + this._headB = this._tailB = new LinkedList(); + //Copy the parent's children (if there are any) + if(parent != null) { + var iterator; + var ot; + if(parent._headA.object != null) { + iterator = parent._headA; + while(iterator != null) { + if(this._tailA.object != null) { + ot = this._tailA; + this._tailA = new LinkedList(); + ot.next = this._tailA; + } + this._tailA.object = iterator.object; + iterator = iterator.next; + } + } + if(parent._headB.object != null) { + iterator = parent._headB; + while(iterator != null) { + if(this._tailB.object != null) { + ot = this._tailB; + this._tailB = new LinkedList(); + ot.next = this._tailB; + } + this._tailB.object = iterator.object; + iterator = iterator.next; + } + } + } else { + QuadTree._min = (this.width + this.height) / (2 * QuadTree.divisions); + } + this._canSubdivide = (this.width > QuadTree._min) || (this.height > QuadTree._min); + //Set up comparison/sort helpers + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + this._leftEdge = this.x; + this._rightEdge = this.x + this.width; + this._halfWidth = this.width / 2; + this._midpointX = this._leftEdge + this._halfWidth; + this._topEdge = this.y; + this._bottomEdge = this.y + this.height; + this._halfHeight = this.height / 2; + this._midpointY = this._topEdge + this._halfHeight; + } + QuadTree.A_LIST = 0; + QuadTree.B_LIST = 1; + QuadTree.prototype.destroy = /** + * Clean up memory. + */ + function () { + this._tailA.destroy(); + this._tailB.destroy(); + this._headA.destroy(); + this._headB.destroy(); + this._tailA = null; + this._tailB = null; + this._headA = null; + this._headB = null; + if(this._northWestTree != null) { + this._northWestTree.destroy(); + } + if(this._northEastTree != null) { + this._northEastTree.destroy(); + } + if(this._southEastTree != null) { + this._southEastTree.destroy(); + } + if(this._southWestTree != null) { + this._southWestTree.destroy(); + } + this._northWestTree = null; + this._northEastTree = null; + this._southEastTree = null; + this._southWestTree = null; + Phaser.QuadTree._object = null; + Phaser.QuadTree._processingCallback = null; + Phaser.QuadTree._notifyCallback = null; + }; + QuadTree.prototype.load = /** + * Load objects and/or groups into the quad tree, and register notify and processing callbacks. + * + * @param {Basic} objectOrGroup1 Any object that is or extends GameObject or Group. + * @param {Basic} objectOrGroup2 Any object that is or extends GameObject or Group. If null, the first parameter will be checked against itself. + * @param {Function} notifyCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject) that is called whenever two objects are found to overlap in world space, and either no processCallback is specified, or the processCallback returns true. + * @param {Function} processCallback A function with the form myFunction(Object1:GameObject,Object2:GameObject):bool that is called whenever two objects are found to overlap in world space. The notifyCallback is only called if this function returns true. See GameObject.separate(). + * @param context The context in which the callbacks will be called + */ + function (objectOrGroup1, objectOrGroup2, notifyCallback, processCallback, context) { + if (typeof objectOrGroup2 === "undefined") { objectOrGroup2 = null; } + if (typeof notifyCallback === "undefined") { notifyCallback = null; } + if (typeof processCallback === "undefined") { processCallback = null; } + if (typeof context === "undefined") { context = null; } + this.add(objectOrGroup1, Phaser.QuadTree.A_LIST); + if(objectOrGroup2 != null) { + this.add(objectOrGroup2, Phaser.QuadTree.B_LIST); + Phaser.QuadTree._useBothLists = true; + } else { + Phaser.QuadTree._useBothLists = false; + } + Phaser.QuadTree._notifyCallback = notifyCallback; + Phaser.QuadTree._processingCallback = processCallback; + Phaser.QuadTree._callbackContext = context; + }; + QuadTree.prototype.add = /** + * Call this function to add an object to the root of the tree. + * This function will recursively add all group members, but + * not the groups themselves. + * + * @param {Basic} objectOrGroup GameObjects are just added, Groups are recursed and their applicable members added accordingly. + * @param {Number} list A uint flag indicating the list to which you want to add the objects. Options are QuadTree.A_LIST and QuadTree.B_LIST. + */ + function (objectOrGroup, list) { + Phaser.QuadTree._list = list; + if(objectOrGroup.isGroup == true) { + var i = 0; + var basic; + var members = objectOrGroup['members']; + var l = objectOrGroup['length']; + while(i < l) { + basic = members[i++]; + if((basic != null) && basic.exists) { + if(basic.isGroup) { + this.add(basic, list); + } else { + Phaser.QuadTree._object = basic; + if(Phaser.QuadTree._object.exists && Phaser.QuadTree._object.allowCollisions) { + this.addObject(); + } + } + } + } + } else { + Phaser.QuadTree._object = objectOrGroup; + if(Phaser.QuadTree._object.exists && Phaser.QuadTree._object.allowCollisions) { + this.addObject(); + } + } + }; + QuadTree.prototype.addObject = /** + * Internal function for recursively navigating and creating the tree + * while adding objects to the appropriate nodes. + */ + function () { + //If this quad (not its children) lies entirely inside this object, add it here + if(!this._canSubdivide || ((this._leftEdge >= Phaser.QuadTree._object.collisionMask.x) && (this._rightEdge <= Phaser.QuadTree._object.collisionMask.right) && (this._topEdge >= Phaser.QuadTree._object.collisionMask.y) && (this._bottomEdge <= Phaser.QuadTree._object.collisionMask.bottom))) { + this.addToList(); + return; + } + //See if the selected object fits completely inside any of the quadrants + if((Phaser.QuadTree._object.collisionMask.x > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.right < this._midpointX)) { + if((Phaser.QuadTree._object.collisionMask.y > this._topEdge) && (Phaser.QuadTree._object.collisionMask.bottom < this._midpointY)) { + if(this._northWestTree == null) { + this._northWestTree = new Phaser.QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northWestTree.addObject(); + return; + } + if((Phaser.QuadTree._object.collisionMask.y > this._midpointY) && (Phaser.QuadTree._object.collisionMask.bottom < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new Phaser.QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + return; + } + } + if((Phaser.QuadTree._object.collisionMask.x > this._midpointX) && (Phaser.QuadTree._object.collisionMask.right < this._rightEdge)) { + if((Phaser.QuadTree._object.collisionMask.y > this._topEdge) && (Phaser.QuadTree._object.collisionMask.bottom < this._midpointY)) { + if(this._northEastTree == null) { + this._northEastTree = new Phaser.QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northEastTree.addObject(); + return; + } + if((Phaser.QuadTree._object.collisionMask.y > this._midpointY) && (Phaser.QuadTree._object.collisionMask.bottom < this._bottomEdge)) { + if(this._southEastTree == null) { + this._southEastTree = new Phaser.QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southEastTree.addObject(); + return; + } + } + //If it wasn't completely contained we have to check out the partial overlaps + if((Phaser.QuadTree._object.collisionMask.right > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.x < this._midpointX) && (Phaser.QuadTree._object.collisionMask.bottom > this._topEdge) && (Phaser.QuadTree._object.collisionMask.y < this._midpointY)) { + if(this._northWestTree == null) { + this._northWestTree = new Phaser.QuadTree(this._leftEdge, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northWestTree.addObject(); + } + if((Phaser.QuadTree._object.collisionMask.right > this._midpointX) && (Phaser.QuadTree._object.collisionMask.x < this._rightEdge) && (Phaser.QuadTree._object.collisionMask.bottom > this._topEdge) && (Phaser.QuadTree._object.collisionMask.y < this._midpointY)) { + if(this._northEastTree == null) { + this._northEastTree = new Phaser.QuadTree(this._midpointX, this._topEdge, this._halfWidth, this._halfHeight, this); + } + this._northEastTree.addObject(); + } + if((Phaser.QuadTree._object.collisionMask.right > this._midpointX) && (Phaser.QuadTree._object.collisionMask.x < this._rightEdge) && (Phaser.QuadTree._object.collisionMask.bottom > this._midpointY) && (Phaser.QuadTree._object.collisionMask.y < this._bottomEdge)) { + if(this._southEastTree == null) { + this._southEastTree = new Phaser.QuadTree(this._midpointX, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southEastTree.addObject(); + } + if((Phaser.QuadTree._object.collisionMask.right > this._leftEdge) && (Phaser.QuadTree._object.collisionMask.x < this._midpointX) && (Phaser.QuadTree._object.collisionMask.bottom > this._midpointY) && (Phaser.QuadTree._object.collisionMask.y < this._bottomEdge)) { + if(this._southWestTree == null) { + this._southWestTree = new Phaser.QuadTree(this._leftEdge, this._midpointY, this._halfWidth, this._halfHeight, this); + } + this._southWestTree.addObject(); + } + }; + QuadTree.prototype.addToList = /** + * Internal function for recursively adding objects to leaf lists. + */ + function () { + var ot; + if(Phaser.QuadTree._list == Phaser.QuadTree.A_LIST) { + if(this._tailA.object != null) { + ot = this._tailA; + this._tailA = new Phaser.LinkedList(); + ot.next = this._tailA; + } + this._tailA.object = Phaser.QuadTree._object; + } else { + if(this._tailB.object != null) { + ot = this._tailB; + this._tailB = new Phaser.LinkedList(); + ot.next = this._tailB; + } + this._tailB.object = Phaser.QuadTree._object; + } + if(!this._canSubdivide) { + return; + } + if(this._northWestTree != null) { + this._northWestTree.addToList(); + } + if(this._northEastTree != null) { + this._northEastTree.addToList(); + } + if(this._southEastTree != null) { + this._southEastTree.addToList(); + } + if(this._southWestTree != null) { + this._southWestTree.addToList(); + } + }; + QuadTree.prototype.execute = /** + * QuadTree's other main function. Call this after adding objects + * using QuadTree.load() to compare the objects that you loaded. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + var overlapProcessed = false; + var iterator; + if(this._headA.object != null) { + iterator = this._headA; + while(iterator != null) { + Phaser.QuadTree._object = iterator.object; + if(Phaser.QuadTree._useBothLists) { + Phaser.QuadTree._iterator = this._headB; + } else { + Phaser.QuadTree._iterator = iterator.next; + } + if(Phaser.QuadTree._object.exists && (Phaser.QuadTree._object.allowCollisions > 0) && (Phaser.QuadTree._iterator != null) && (Phaser.QuadTree._iterator.object != null) && Phaser.QuadTree._iterator.object.exists && this.overlapNode()) { + overlapProcessed = true; + } + iterator = iterator.next; + } + } + //Advance through the tree by calling overlap on each child + if((this._northWestTree != null) && this._northWestTree.execute()) { + overlapProcessed = true; + } + if((this._northEastTree != null) && this._northEastTree.execute()) { + overlapProcessed = true; + } + if((this._southEastTree != null) && this._southEastTree.execute()) { + overlapProcessed = true; + } + if((this._southWestTree != null) && this._southWestTree.execute()) { + overlapProcessed = true; + } + return overlapProcessed; + }; + QuadTree.prototype.overlapNode = /** + * A private for comparing an object against the contents of a node. + * + * @return {Boolean} Whether or not any overlaps were found. + */ + function () { + //Walk the list and check for overlaps + var overlapProcessed = false; + var checkObject; + while(Phaser.QuadTree._iterator != null) { + if(!Phaser.QuadTree._object.exists || (Phaser.QuadTree._object.allowCollisions <= 0)) { + break; + } + checkObject = Phaser.QuadTree._iterator.object; + if((Phaser.QuadTree._object === checkObject) || !checkObject.exists || (checkObject.allowCollisions <= 0)) { + Phaser.QuadTree._iterator = Phaser.QuadTree._iterator.next; + continue; + } + if(Phaser.QuadTree._object.collisionMask.checkHullIntersection(checkObject.collisionMask)) { + //Execute callback functions if they exist + if((Phaser.QuadTree._processingCallback == null) || Phaser.QuadTree._processingCallback(Phaser.QuadTree._object, checkObject)) { + overlapProcessed = true; + } + if(overlapProcessed && (Phaser.QuadTree._notifyCallback != null)) { + if(Phaser.QuadTree._callbackContext !== null) { + Phaser.QuadTree._notifyCallback.call(Phaser.QuadTree._callbackContext, Phaser.QuadTree._object, checkObject); + } else { + Phaser.QuadTree._notifyCallback(Phaser.QuadTree._object, checkObject); + } + } + } + Phaser.QuadTree._iterator = Phaser.QuadTree._iterator.next; + } + return overlapProcessed; + }; + return QuadTree; + })(Phaser.Rectangle); + Phaser.QuadTree = QuadTree; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/RandomDataGenerator.js b/Phaser/system/RandomDataGenerator.js new file mode 100644 index 00000000..d891ab0e --- /dev/null +++ b/Phaser/system/RandomDataGenerator.js @@ -0,0 +1,227 @@ +/// +/** +* Phaser - RandomDataGenerator +* +* An extremely useful repeatable random data generator. Access it via Game.rnd +* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense +* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript +*/ +var Phaser; +(function (Phaser) { + var RandomDataGenerator = (function () { + /** + * @constructor + * @param {Array} seeds + * @return {Phaser.RandomDataGenerator} + */ + function RandomDataGenerator(seeds) { + if (typeof seeds === "undefined") { seeds = []; } + /** + * @property c + * @type Number + * @private + */ + this.c = 1; + this.sow(seeds); + } + RandomDataGenerator.prototype.uint32 = /** + * @method uint32 + * @private + */ + function () { + return this.rnd.apply(this) * 0x100000000;// 2^32 + + }; + RandomDataGenerator.prototype.fract32 = /** + * @method fract32 + * @private + */ + function () { + return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53 + + }; + RandomDataGenerator.prototype.rnd = // private random helper + /** + * @method rnd + * @private + */ + function () { + var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10;// 2^-32 + + this.c = t | 0; + this.s0 = this.s1; + this.s1 = this.s2; + this.s2 = t - this.c; + return this.s2; + }; + RandomDataGenerator.prototype.hash = /** + * @method hash + * @param {Any} data + * @private + */ + function (data) { + var h, i, n; + n = 0xefc8249d; + data = data.toString(); + for(i = 0; i < data.length; i++) { + n += data.charCodeAt(i); + h = 0.02519603282416938 * n; + n = h >>> 0; + h -= n; + h *= n; + n = h >>> 0; + h -= n; + n += h * 0x100000000// 2^32 + ; + } + return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 + + }; + RandomDataGenerator.prototype.sow = /** + * Reset the seed of the random data generator + * @method sow + * @param {Array} seeds + */ + function (seeds) { + if (typeof seeds === "undefined") { seeds = []; } + this.s0 = this.hash(' '); + this.s1 = this.hash(this.s0); + this.s2 = this.hash(this.s1); + var seed; + for(var i = 0; seed = seeds[i++]; ) { + this.s0 -= this.hash(seed); + this.s0 += ~~(this.s0 < 0); + this.s1 -= this.hash(seed); + this.s1 += ~~(this.s1 < 0); + this.s2 -= this.hash(seed); + this.s2 += ~~(this.s2 < 0); + } + }; + Object.defineProperty(RandomDataGenerator.prototype, "integer", { + get: /** + * Returns a random integer between 0 and 2^32 + * @method integer + * @return {Number} + */ + function () { + return this.uint32(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "frac", { + get: /** + * Returns a random real number between 0 and 1 + * @method frac + * @return {Number} + */ + function () { + return this.fract32(); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "real", { + get: /** + * Returns a random real number between 0 and 2^32 + * @method real + * @return {Number} + */ + function () { + return this.uint32() + this.fract32(); + }, + enumerable: true, + configurable: true + }); + RandomDataGenerator.prototype.integerInRange = /** + * Returns a random integer between min and max + * @method integerInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + function (min, max) { + return Math.floor(this.realInRange(min, max)); + }; + RandomDataGenerator.prototype.realInRange = /** + * Returns a random real number between min and max + * @method realInRange + * @param {Number} min + * @param {Number} max + * @return {Number} + */ + function (min, max) { + min = min || 0; + max = max || 0; + return this.frac * (max - min) + min; + }; + Object.defineProperty(RandomDataGenerator.prototype, "normal", { + get: /** + * Returns a random real number between -1 and 1 + * @method normal + * @return {Number} + */ + function () { + return 1 - 2 * this.frac; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(RandomDataGenerator.prototype, "uuid", { + get: /** + * Returns a valid v4 UUID hex string (from https://gist.github.com/1308368) + * @method uuid + * @return {String} + */ + function () { + var a, b; + for(b = a = ''; a++ < 36; b += ~a % 5 | a * 3 & 4 ? (a ^ 15 ? 8 ^ this.frac * (a ^ 20 ? 16 : 4) : 4).toString(16) : '-') { + ; + } + return b; + }, + enumerable: true, + configurable: true + }); + RandomDataGenerator.prototype.pick = /** + * Returns a random member of `array` + * @method pick + * @param {Any} array + */ + function (array) { + return array[this.integerInRange(0, array.length)]; + }; + RandomDataGenerator.prototype.weightedPick = /** + * Returns a random member of `array`, favoring the earlier entries + * @method weightedPick + * @param {Any} array + */ + function (array) { + return array[~~(Math.pow(this.frac, 2) * array.length)]; + }; + RandomDataGenerator.prototype.timestamp = /** + * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified + * @method timestamp + * @param {Number} min + * @param {Number} max + */ + function (min, max) { + if (typeof min === "undefined") { min = 946684800000; } + if (typeof max === "undefined") { max = 1577862000000; } + return this.realInRange(min, max); + }; + Object.defineProperty(RandomDataGenerator.prototype, "angle", { + get: /** + * Returns a random angle between -180 and 180 + * @method angle + */ + function () { + return this.integerInRange(-180, 180); + }, + enumerable: true, + configurable: true + }); + return RandomDataGenerator; + })(); + Phaser.RandomDataGenerator = RandomDataGenerator; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/Sound.js b/Phaser/system/Sound.js new file mode 100644 index 00000000..c7ef5927 --- /dev/null +++ b/Phaser/system/Sound.js @@ -0,0 +1,80 @@ +/// +/// +/** +* Phaser - Sound +* +* A Sound file, used by the Game.SoundManager for playback. +*/ +var Phaser; +(function (Phaser) { + var Sound = (function () { + function Sound(context, gainNode, data, volume, loop) { + if (typeof volume === "undefined") { volume = 1; } + if (typeof loop === "undefined") { loop = false; } + this.loop = false; + this.isPlaying = false; + this.isDecoding = false; + this._context = context; + this._gainNode = gainNode; + this._buffer = data; + this._volume = volume; + this.loop = loop; + // Local volume control + if(this._context !== null) { + this._localGainNode = this._context.createGainNode(); + this._localGainNode.connect(this._gainNode); + this._localGainNode.gain.value = this._volume; + } + if(this._buffer === null) { + this.isDecoding = true; + } else { + this.play(); + } + } + Sound.prototype.setDecodedBuffer = function (data) { + this._buffer = data; + this.isDecoding = false; + //this.play(); + }; + Sound.prototype.play = function () { + if(this._buffer === null || this.isDecoding === true) { + return; + } + this._sound = this._context.createBufferSource(); + this._sound.buffer = this._buffer; + this._sound.connect(this._localGainNode); + if(this.loop) { + this._sound.loop = true; + } + this._sound.noteOn(0)// the zero is vitally important, crashes iOS6 without it + ; + this.duration = this._sound.buffer.duration; + this.isPlaying = true; + }; + Sound.prototype.stop = function () { + if(this.isPlaying === true) { + this.isPlaying = false; + this._sound.noteOff(0); + } + }; + Sound.prototype.mute = function () { + this._localGainNode.gain.value = 0; + }; + Sound.prototype.unmute = function () { + this._localGainNode.gain.value = this._volume; + }; + Object.defineProperty(Sound.prototype, "volume", { + get: function () { + return this._volume; + }, + set: function (value) { + this._volume = value; + this._localGainNode.gain.value = this._volume; + }, + enumerable: true, + configurable: true + }); + return Sound; + })(); + Phaser.Sound = Sound; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/Tile.js b/Phaser/system/Tile.js new file mode 100644 index 00000000..3f02b81b --- /dev/null +++ b/Phaser/system/Tile.js @@ -0,0 +1,123 @@ +/// +/** +* Phaser - Tile +* +* A Tile is a single representation of a tile within a Tilemap +*/ +var Phaser; +(function (Phaser) { + var Tile = (function () { + /** + * Tile constructor + * Create a new Tile. + * + * @param tilemap {Tilemap} the tilemap this tile belongs to. + * @param index {number} The index of this tile type in the core map data. + * @param width {number} Width of the tile. + * @param height number} Height of the tile. + */ + function Tile(game, tilemap, index, width, height) { + /** + * The virtual mass of the tile. + * @type {number} + */ + this.mass = 1.0; + /** + * Indicating collide with any object on the left. + * @type {boolean} + */ + this.collideLeft = false; + /** + * Indicating collide with any object on the right. + * @type {boolean} + */ + this.collideRight = false; + /** + * Indicating collide with any object on the top. + * @type {boolean} + */ + this.collideUp = false; + /** + * Indicating collide with any object on the bottom. + * @type {boolean} + */ + this.collideDown = false; + /** + * Enable separation at x-axis. + * @type {boolean} + */ + this.separateX = true; + /** + * Enable separation at y-axis. + * @type {boolean} + */ + this.separateY = true; + this._game = game; + this.tilemap = tilemap; + this.index = index; + this.width = width; + this.height = height; + this.allowCollisions = Collision.NONE; + } + Tile.prototype.destroy = /** + * Clean up memory. + */ + function () { + this.tilemap = null; + }; + Tile.prototype.setCollision = /** + * Set collision configs. + * @param collision {number} Bit field of flags. (see Tile.allowCollision) + * @param resetCollisions {boolean} Reset collision flags before set. + * @param separateX {boolean} Enable seprate at x-axis. + * @param separateY {boolean} Enable seprate at y-axis. + */ + function (collision, resetCollisions, separateX, separateY) { + if(resetCollisions) { + this.resetCollision(); + } + this.separateX = separateX; + this.separateY = separateY; + this.allowCollisions = collision; + if(collision & Phaser.Collision.ANY) { + this.collideLeft = true; + this.collideRight = true; + this.collideUp = true; + this.collideDown = true; + return; + } + if(collision & Phaser.Collision.LEFT || collision & Phaser.Collision.WALL) { + this.collideLeft = true; + } + if(collision & Phaser.Collision.RIGHT || collision & Phaser.Collision.WALL) { + this.collideRight = true; + } + if(collision & Phaser.Collision.UP || collision & Phaser.Collision.CEILING) { + this.collideUp = true; + } + if(collision & Phaser.Collision.DOWN || collision & Phaser.Collision.CEILING) { + this.collideDown = true; + } + }; + Tile.prototype.resetCollision = /** + * Reset collision status flags. + */ + function () { + this.allowCollisions = Phaser.Collision.NONE; + this.collideLeft = false; + this.collideRight = false; + this.collideUp = false; + this.collideDown = false; + }; + Tile.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the object. + **/ + function () { + return "[{Tiled (index=" + this.index + " collisions=" + this.allowCollisions + " width=" + this.width + " height=" + this.height + ")}]"; + }; + return Tile; + })(); + Phaser.Tile = Tile; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/TilemapLayer.js b/Phaser/system/TilemapLayer.js new file mode 100644 index 00000000..f789fba9 --- /dev/null +++ b/Phaser/system/TilemapLayer.js @@ -0,0 +1,455 @@ +/// +/** +* Phaser - TilemapLayer +* +* A Tilemap Layer. Tiled format maps can have multiple overlapping layers. +*/ +var Phaser; +(function (Phaser) { + var TilemapLayer = (function () { + /** + * TilemapLayer constructor + * Create a new TilemapLayer. + * + * @param game {Phaser.Game} Current game instance. + * @param parent {Tilemap} The tilemap that contains this layer. + * @param key {string} Asset key for this map. + * @param mapFormat {number} Format of this map data, available: Tilemap.FORMAT_CSV or Tilemap.FORMAT_TILED_JSON. + * @param name {string} Name of this layer, so you can get this layer by its name. + * @param tileWidth {number} Width of tiles in this map. + * @param tileHeight {number} Height of tiles in this map. + */ + function TilemapLayer(game, parent, key, mapFormat, name, tileWidth, tileHeight) { + this._startX = 0; + this._startY = 0; + this._maxX = 0; + this._maxY = 0; + this._tx = 0; + this._ty = 0; + this._dx = 0; + this._dy = 0; + this._oldCameraX = 0; + this._oldCameraY = 0; + /** + * Opacity of this layer. + * @type {number} + */ + this.alpha = 1; + /** + * Controls whether update() and draw() are automatically called. + * @type {boolean} + */ + this.exists = true; + /** + * Controls whether draw() are automatically called. + * @type {boolean} + */ + this.visible = true; + /** + * How many tiles in each row. + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + this.widthInTiles = 0; + /** + * How many tiles in each column. + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + this.heightInTiles = 0; + /** + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + this.widthInPixels = 0; + /** + * Read-only variable, do NOT recommend changing after the map is loaded! + * @type {number} + */ + this.heightInPixels = 0; + /** + * Distance between REAL tiles to the tileset texture bound. + * @type {number} + */ + this.tileMargin = 0; + /** + * Distance between every 2 neighbor tile in the tileset texture. + * @type {number} + */ + this.tileSpacing = 0; + this._game = game; + this._parent = parent; + this.name = name; + this.mapFormat = mapFormat; + this.tileWidth = tileWidth; + this.tileHeight = tileHeight; + this.boundsInTiles = new Rectangle(); + //this.scrollFactor = new MicroPoint(1, 1); + this.canvas = game.stage.canvas; + this.context = game.stage.context; + this.mapData = []; + this._tempTileBlock = []; + this._texture = this._game.cache.getImage(key); + } + TilemapLayer.prototype.putTile = /** + * Set a specific tile with its x and y in tiles. + * @param x {number} X position of this tile. + * @param y {number} Y position of this tile. + * @param index {number} The index of this tile type in the core map data. + */ + function (x, y, index) { + x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; + y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; + if(y >= 0 && y < this.mapData.length) { + if(x >= 0 && x < this.mapData[y].length) { + this.mapData[y][x] = index; + } + } + }; + TilemapLayer.prototype.swapTile = /** + * Swap tiles with 2 kinds of indexes. + * @param tileA {number} First tile index. + * @param tileB {number} Second tile index. + * @param [x] {number} specify a rectangle of tiles to operate. The x position in tiles of rectangle's left-top corner. + * @param [y] {number} specify a rectangle of tiles to operate. The y position in tiles of rectangle's left-top corner. + * @param [width] {number} specify a rectangle of tiles to operate. The width in tiles. + * @param [height] {number} specify a rectangle of tiles to operate. The height in tiles. + */ + function (tileA, tileB, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = this.widthInTiles; } + if (typeof height === "undefined") { height = this.heightInTiles; } + this.getTempBlock(x, y, width, height); + for(var r = 0; r < this._tempTileBlock.length; r++) { + // First sweep marking tileA as needing a new index + if(this._tempTileBlock[r].tile.index == tileA) { + this._tempTileBlock[r].newIndex = true; + } + // In the same pass we can swap tileB to tileA + if(this._tempTileBlock[r].tile.index == tileB) { + this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileA; + } + } + for(var r = 0; r < this._tempTileBlock.length; r++) { + // And now swap our newIndex tiles for tileB + if(this._tempTileBlock[r].newIndex == true) { + this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; + } + } + }; + TilemapLayer.prototype.fillTile = /** + * Fill a tile block with a specific tile index. + * @param index {number} Index of tiles you want to fill with. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + function (index, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = this.widthInTiles; } + if (typeof height === "undefined") { height = this.heightInTiles; } + this.getTempBlock(x, y, width, height); + for(var r = 0; r < this._tempTileBlock.length; r++) { + this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = index; + } + }; + TilemapLayer.prototype.randomiseTiles = /** + * Set random tiles to a specific tile block. + * @param tiles {number[]} Tiles with indexes in this array will be randomly set to the given block. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + function (tiles, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = this.widthInTiles; } + if (typeof height === "undefined") { height = this.heightInTiles; } + this.getTempBlock(x, y, width, height); + for(var r = 0; r < this._tempTileBlock.length; r++) { + this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = this._game.math.getRandom(tiles); + } + }; + TilemapLayer.prototype.replaceTile = /** + * Replace one kind of tiles to another kind. + * @param tileA {number} Index of tiles you want to replace. + * @param tileB {number} Index of tiles you want to set. + * @param [x] {number} x position (in tiles) of block's left-top corner. + * @param [y] {number} y position (in tiles) of block's left-top corner. + * @param [width] {number} width of block. + * @param [height] {number} height of block. + */ + function (tileA, tileB, x, y, width, height) { + if (typeof x === "undefined") { x = 0; } + if (typeof y === "undefined") { y = 0; } + if (typeof width === "undefined") { width = this.widthInTiles; } + if (typeof height === "undefined") { height = this.heightInTiles; } + this.getTempBlock(x, y, width, height); + for(var r = 0; r < this._tempTileBlock.length; r++) { + if(this._tempTileBlock[r].tile.index == tileA) { + this.mapData[this._tempTileBlock[r].y][this._tempTileBlock[r].x] = tileB; + } + } + }; + TilemapLayer.prototype.getTileBlock = /** + * Get a tile block with specific position and size.(both are in tiles) + * @param x {number} X position of block's left-top corner. + * @param y {number} Y position of block's left-top corner. + * @param width {number} Width of block. + * @param height {number} Height of block. + */ + function (x, y, width, height) { + var output = []; + this.getTempBlock(x, y, width, height); + for(var r = 0; r < this._tempTileBlock.length; r++) { + output.push({ + x: this._tempTileBlock[r].x, + y: this._tempTileBlock[r].y, + tile: this._tempTileBlock[r].tile + }); + } + return output; + }; + TilemapLayer.prototype.getTileFromWorldXY = /** + * Get a tile with specific position (in world coordinate). (thus you give a position of a point which is within the tile) + * @param x {number} X position of the point in target tile. + * @param x {number} Y position of the point in target tile. + */ + function (x, y) { + x = this._game.math.snapToFloor(x, this.tileWidth) / this.tileWidth; + y = this._game.math.snapToFloor(y, this.tileHeight) / this.tileHeight; + return this.getTileIndex(x, y); + }; + TilemapLayer.prototype.getTileOverlaps = /** + * Get tiles overlaps the given object. + * @param object {GameObject} Tiles you want to get that overlaps this. + * @return {array} Array with tiles informations. (Each contains x, y and the tile.) + */ + function (object) { + // If the object is outside of the world coordinates then abort the check (tilemap has to exist within world bounds) + if(object.collisionMask.x < 0 || object.collisionMask.x > this.widthInPixels || object.collisionMask.y < 0 || object.collisionMask.bottom > this.heightInPixels) { + return; + } + // What tiles do we need to check against? + this._tempTileX = this._game.math.snapToFloor(object.collisionMask.x, this.tileWidth) / this.tileWidth; + this._tempTileY = this._game.math.snapToFloor(object.collisionMask.y, this.tileHeight) / this.tileHeight; + this._tempTileW = (this._game.math.snapToCeil(object.collisionMask.width, this.tileWidth) + this.tileWidth) / this.tileWidth; + this._tempTileH = (this._game.math.snapToCeil(object.collisionMask.height, this.tileHeight) + this.tileHeight) / this.tileHeight; + // Loop through the tiles we've got and check overlaps accordingly (the results are stored in this._tempTileBlock) + this._tempBlockResults = []; + this.getTempBlock(this._tempTileX, this._tempTileY, this._tempTileW, this._tempTileH, true); + Phaser.Collision.TILE_OVERLAP = false; + for(var r = 0; r < this._tempTileBlock.length; r++) { + if(Phaser.Collision.separateTile(object, this._tempTileBlock[r].x * this.tileWidth, this._tempTileBlock[r].y * this.tileHeight, this.tileWidth, this.tileHeight, this._tempTileBlock[r].tile.mass, this._tempTileBlock[r].tile.collideLeft, this._tempTileBlock[r].tile.collideRight, this._tempTileBlock[r].tile.collideUp, this._tempTileBlock[r].tile.collideDown, this._tempTileBlock[r].tile.separateX, this._tempTileBlock[r].tile.separateY) == true) { + this._tempBlockResults.push({ + x: this._tempTileBlock[r].x, + y: this._tempTileBlock[r].y, + tile: this._tempTileBlock[r].tile + }); + } + } + return this._tempBlockResults; + }; + TilemapLayer.prototype.getTempBlock = /** + * Get a tile block with its position and size. (This method does not return, it'll set result to _tempTileBlock) + * @param x {number} X position of block's left-top corner. + * @param y {number} Y position of block's left-top corner. + * @param width {number} Width of block. + * @param height {number} Height of block. + * @param collisionOnly {boolean} Whethor or not ONLY return tiles which will collide (its allowCollisions value is not Collision.NONE). + */ + function (x, y, width, height, collisionOnly) { + if (typeof collisionOnly === "undefined") { collisionOnly = false; } + if(x < 0) { + x = 0; + } + if(y < 0) { + y = 0; + } + if(width > this.widthInTiles) { + width = this.widthInTiles; + } + if(height > this.heightInTiles) { + height = this.heightInTiles; + } + this._tempTileBlock = []; + for(var ty = y; ty < y + height; ty++) { + for(var tx = x; tx < x + width; tx++) { + if(collisionOnly) { + // We only want to consider the tile for checking if you can actually collide with it + if(this.mapData[ty] && this.mapData[ty][tx] && this._parent.tiles[this.mapData[ty][tx]].allowCollisions != Phaser.Collision.NONE) { + this._tempTileBlock.push({ + x: tx, + y: ty, + tile: this._parent.tiles[this.mapData[ty][tx]] + }); + } + } else { + if(this.mapData[ty] && this.mapData[ty][tx]) { + this._tempTileBlock.push({ + x: tx, + y: ty, + tile: this._parent.tiles[this.mapData[ty][tx]] + }); + } + } + } + } + }; + TilemapLayer.prototype.getTileIndex = /** + * Get the tile index of specific position (in tiles). + * @param x {number} X position of the tile. + * @param y {number} Y position of the tile. + * @return {number} Index of the tile at that position. Return null if there isn't a tile there. + */ + function (x, y) { + if(y >= 0 && y < this.mapData.length) { + if(x >= 0 && x < this.mapData[y].length) { + return this.mapData[y][x]; + } + } + return null; + }; + TilemapLayer.prototype.addColumn = /** + * Add a column of tiles into the layer. + * @param column {string[]/number[]} An array of tile indexes to be added. + */ + function (column) { + var data = []; + for(var c = 0; c < column.length; c++) { + data[c] = parseInt(column[c]); + } + if(this.widthInTiles == 0) { + this.widthInTiles = data.length; + this.widthInPixels = this.widthInTiles * this.tileWidth; + } + this.mapData.push(data); + this.heightInTiles++; + this.heightInPixels += this.tileHeight; + }; + TilemapLayer.prototype.updateBounds = /** + * Update boundsInTiles with widthInTiles and heightInTiles. + */ + function () { + this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles); + }; + TilemapLayer.prototype.parseTileOffsets = /** + * Parse tile offsets from map data. + * @return {number} length of _tileOffsets array. + */ + function () { + this._tileOffsets = []; + var i = 0; + if(this.mapFormat == Phaser.Tilemap.FORMAT_TILED_JSON) { + // For some reason Tiled counts from 1 not 0 + this._tileOffsets[0] = null; + i = 1; + } + for(var ty = this.tileMargin; ty < this._texture.height; ty += (this.tileHeight + this.tileSpacing)) { + for(var tx = this.tileMargin; tx < this._texture.width; tx += (this.tileWidth + this.tileSpacing)) { + this._tileOffsets[i] = { + x: tx, + y: ty + }; + i++; + } + } + return this._tileOffsets.length; + }; + TilemapLayer.prototype.renderDebugInfo = function (x, y, color) { + if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } + this.context.fillStyle = color; + this.context.fillText('TilemapLayer: ' + this.name, x, y); + this.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14); + this.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28); + this.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42); + }; + TilemapLayer.prototype.render = /** + * Render this layer to a specific camera with offset to camera. + * @param camera {Camera} The camera the layer is going to be rendered. + * @param dx {number} X offset to the camera. + * @param dy {number} Y offset to the camera. + * @return {boolean} Return false if layer is invisible or has a too low opacity(will stop rendering), return true if succeed. + */ + function (camera, dx, dy) { + if(this.visible === false || this.alpha < 0.1) { + return false; + } + // Work out how many tiles we can fit into our camera and round it up for the edges + this._maxX = this._game.math.ceil(camera.width / this.tileWidth) + 1; + this._maxY = this._game.math.ceil(camera.height / this.tileHeight) + 1; + // And now work out where in the tilemap the camera actually is + this._startX = this._game.math.floor(camera.worldView.x / this.tileWidth); + this._startY = this._game.math.floor(camera.worldView.y / this.tileHeight); + // Tilemap bounds check + if(this._startX < 0) { + this._startX = 0; + } + if(this._startY < 0) { + this._startY = 0; + } + if(this._maxX > this.widthInTiles) { + this._maxX = this.widthInTiles; + } + if(this._maxY > this.heightInTiles) { + this._maxY = this.heightInTiles; + } + if(this._startX + this._maxX > this.widthInTiles) { + this._startX = this.widthInTiles - this._maxX; + } + if(this._startY + this._maxY > this.heightInTiles) { + this._startY = this.heightInTiles - this._maxY; + } + // Finally get the offset to avoid the blocky movement + this._dx = dx; + this._dy = dy; + this._dx += -(camera.worldView.x - (this._startX * this.tileWidth)); + this._dy += -(camera.worldView.y - (this._startY * this.tileHeight)); + this._tx = this._dx; + this._ty = this._dy; + // Apply camera difference + /* + if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0) + { + this._dx -= (camera.worldView.x * this.scrollFactor.x); + this._dy -= (camera.worldView.y * this.scrollFactor.y); + } + */ + // Alpha + if(this.alpha !== 1) { + var globalAlpha = this.context.globalAlpha; + this.context.globalAlpha = this.alpha; + } + for(var row = this._startY; row < this._startY + this._maxY; row++) { + this._columnData = this.mapData[row]; + for(var tile = this._startX; tile < this._startX + this._maxX; tile++) { + if(this._tileOffsets[this._columnData[tile]]) { + this.context.drawImage(this._texture, // Source Image + this._tileOffsets[this._columnData[tile]].x, // Source X (location within the source image) + this._tileOffsets[this._columnData[tile]].y, // Source Y + this.tileWidth, // Source Width + this.tileHeight, // Source Height + this._tx, // Destination X (where on the canvas it'll be drawn) + this._ty, // Destination Y + this.tileWidth, // Destination Width (always same as Source Width unless scaled) + this.tileHeight); + // Destination Height (always same as Source Height unless scaled) + } + this._tx += this.tileWidth; + } + this._tx = this._dx; + this._ty += this.tileHeight; + } + if(globalAlpha > -1) { + this.context.globalAlpha = globalAlpha; + } + return true; + }; + return TilemapLayer; + })(); + Phaser.TilemapLayer = TilemapLayer; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/Tween.js b/Phaser/system/Tween.js new file mode 100644 index 00000000..8159d3ab --- /dev/null +++ b/Phaser/system/Tween.js @@ -0,0 +1,173 @@ +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/** +* Phaser - Tween +* +* Based heavily on tween.js by sole (https://github.com/sole/tween.js) converted to TypeScript and integrated into Phaser +*/ +var Phaser; +(function (Phaser) { + var Tween = (function () { + function Tween(object, game) { + this._object = null; + this._pausedTime = 0; + this._valuesStart = { + }; + this._valuesEnd = { + }; + this._duration = 1000; + this._delayTime = 0; + this._startTime = null; + this._chainedTweens = []; + this._object = object; + this._game = game; + this._manager = this._game.tweens; + this._interpolationFunction = this._game.math.linearInterpolation; + this._easingFunction = Phaser.Easing.Linear.None; + this._chainedTweens = []; + this.onStart = new Phaser.Signal(); + this.onUpdate = new Phaser.Signal(); + this.onComplete = new Phaser.Signal(); + } + Tween.prototype.to = function (properties, duration, ease, autoStart) { + if (typeof duration === "undefined") { duration = 1000; } + if (typeof ease === "undefined") { ease = null; } + if (typeof autoStart === "undefined") { autoStart = false; } + this._duration = duration; + // If properties isn't an object this will fail, sanity check it here somehow? + this._valuesEnd = properties; + if(ease !== null) { + this._easingFunction = ease; + } + if(autoStart === true) { + return this.start(); + } else { + return this; + } + }; + Tween.prototype.start = function () { + if(this._game === null || this._object === null) { + return; + } + this._manager.add(this); + this.onStart.dispatch(this._object); + this._startTime = this._game.time.now + this._delayTime; + for(var property in this._valuesEnd) { + // This prevents the interpolation of null values or of non-existing properties + if(this._object[property] === null || !(property in this._object)) { + throw Error('Phaser.Tween interpolation of null value of non-existing property'); + continue; + } + // check if an Array was provided as property value + if(this._valuesEnd[property] instanceof Array) { + if(this._valuesEnd[property].length === 0) { + continue; + } + // create a local copy of the Array with the start value at the front + this._valuesEnd[property] = [ + this._object[property] + ].concat(this._valuesEnd[property]); + } + this._valuesStart[property] = this._object[property]; + } + return this; + }; + Tween.prototype.stop = function () { + if(this._manager !== null) { + this._manager.remove(this); + } + this.onComplete.dispose(); + return this; + }; + Object.defineProperty(Tween.prototype, "parent", { + set: function (value) { + this._game = value; + this._manager = this._game.tweens; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "delay", { + get: function () { + return this._delayTime; + }, + set: function (amount) { + this._delayTime = amount; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "easing", { + get: function () { + return this._easingFunction; + }, + set: function (easing) { + this._easingFunction = easing; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Tween.prototype, "interpolation", { + get: function () { + return this._interpolationFunction; + }, + set: function (interpolation) { + this._interpolationFunction = interpolation; + }, + enumerable: true, + configurable: true + }); + Tween.prototype.chain = function (tween) { + this._chainedTweens.push(tween); + return this; + }; + Tween.prototype.update = function (time) { + if(this._game.paused == true) { + if(this._pausedTime == 0) { + this._pausedTime = time; + } + } else { + // Ok we aren't paused, but was there some time gained? + if(this._pausedTime > 0) { + this._startTime += (time - this._pausedTime); + this._pausedTime = 0; + } + } + if(time < this._startTime) { + return true; + } + var elapsed = (time - this._startTime) / this._duration; + elapsed = elapsed > 1 ? 1 : elapsed; + var value = this._easingFunction(elapsed); + for(var property in this._valuesStart) { + // Add checks for object, array, numeric up front + if(this._valuesEnd[property] instanceof Array) { + this._object[property] = this._interpolationFunction(this._valuesEnd[property], value); + } else { + this._object[property] = this._valuesStart[property] + (this._valuesEnd[property] - this._valuesStart[property]) * value; + } + } + this.onUpdate.dispatch(this._object, value); + if(elapsed == 1) { + this.onComplete.dispatch(this._object); + for(var i = 0; i < this._chainedTweens.length; i++) { + this._chainedTweens[i].start(); + } + return false; + } + return true; + }; + return Tween; + })(); + Phaser.Tween = Tween; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/animation/Animation.js b/Phaser/system/animation/Animation.js new file mode 100644 index 00000000..a3ca43a7 --- /dev/null +++ b/Phaser/system/animation/Animation.js @@ -0,0 +1,107 @@ +/// +/** +* Phaser - Animation +* +* An Animation is a single animation. It is created by the AnimationManager and belongs to Sprite objects. +*/ +var Phaser; +(function (Phaser) { + var Animation = (function () { + function Animation(game, parent, frameData, name, frames, delay, looped) { + this._game = game; + this._parent = parent; + this._frames = frames; + this._frameData = frameData; + this.name = name; + this.delay = 1000 / delay; + this.looped = looped; + this.isFinished = false; + this.isPlaying = false; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } + Object.defineProperty(Animation.prototype, "frameTotal", { + get: function () { + return this._frames.length; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Animation.prototype, "frame", { + get: function () { + return this._frameIndex; + }, + set: function (value) { + this.currentFrame = this._frameData.getFrame(value); + if(this.currentFrame !== null) { + this._parent.bounds.width = this.currentFrame.width; + this._parent.bounds.height = this.currentFrame.height; + this._frameIndex = value; + } + }, + enumerable: true, + configurable: true + }); + Animation.prototype.play = function (frameRate, loop) { + if (typeof frameRate === "undefined") { frameRate = null; } + if(frameRate !== null) { + this.delay = 1000 / frameRate; + } + if(loop !== undefined) { + this.looped = loop; + } + this.isPlaying = true; + this.isFinished = false; + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + }; + Animation.prototype.restart = function () { + this.isPlaying = true; + this.isFinished = false; + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + }; + Animation.prototype.stop = function () { + this.isPlaying = false; + this.isFinished = true; + }; + Animation.prototype.update = function () { + if(this.isPlaying == true && this._game.time.now >= this._timeNextFrame) { + this._frameIndex++; + if(this._frameIndex == this._frames.length) { + if(this.looped) { + this._frameIndex = 0; + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } else { + this.onComplete(); + } + } else { + this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); + } + this._timeLastFrame = this._game.time.now; + this._timeNextFrame = this._game.time.now + this.delay; + return true; + } + return false; + }; + Animation.prototype.destroy = function () { + this._game = null; + this._parent = null; + this._frames = null; + this._frameData = null; + this.currentFrame = null; + this.isPlaying = false; + }; + Animation.prototype.onComplete = function () { + this.isPlaying = false; + this.isFinished = true; + // callback + }; + return Animation; + })(); + Phaser.Animation = Animation; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/animation/AnimationLoader.js b/Phaser/system/animation/AnimationLoader.js new file mode 100644 index 00000000..a3e20884 --- /dev/null +++ b/Phaser/system/animation/AnimationLoader.js @@ -0,0 +1,58 @@ +/// +/** +* Phaser - AnimationLoader +* +* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. +*/ +var Phaser; +(function (Phaser) { + var AnimationLoader = (function () { + function AnimationLoader() { } + AnimationLoader.parseSpriteSheet = function parseSpriteSheet(game, key, frameWidth, frameHeight, frameMax) { + // How big is our image? + var img = game.cache.getImage(key); + if(img == null) { + return null; + } + var width = img.width; + var height = img.height; + var row = Math.round(width / frameWidth); + var column = Math.round(height / frameHeight); + var total = row * column; + if(frameMax !== -1) { + total = frameMax; + } + // Zero or smaller than frame sizes? + if(width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) { + return null; + } + // Let's create some frames then + var data = new Phaser.FrameData(); + var x = 0; + var y = 0; + for(var i = 0; i < total; i++) { + data.addFrame(new Phaser.Frame(x, y, frameWidth, frameHeight, '')); + x += frameWidth; + if(x === width) { + x = 0; + y += frameHeight; + } + } + return data; + }; + AnimationLoader.parseJSONData = function parseJSONData(game, json) { + // Let's create some frames then + var data = new Phaser.FrameData(); + // By this stage frames is a fully parsed array + var frames = json; + var newFrame; + for(var i = 0; i < frames.length; i++) { + newFrame = data.addFrame(new Phaser.Frame(frames[i].frame.x, frames[i].frame.y, frames[i].frame.w, frames[i].frame.h, frames[i].filename)); + newFrame.setTrim(frames[i].trimmed, frames[i].sourceSize.w, frames[i].sourceSize.h, frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].spriteSourceSize.w, frames[i].spriteSourceSize.h); + } + return data; + }; + return AnimationLoader; + })(); + Phaser.AnimationLoader = AnimationLoader; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/animation/Frame.js b/Phaser/system/animation/Frame.js new file mode 100644 index 00000000..d3bb2904 --- /dev/null +++ b/Phaser/system/animation/Frame.js @@ -0,0 +1,40 @@ +/// +/** +* Phaser - Frame +* +* A Frame is a single frame of an animation and is part of a FrameData collection. +*/ +var Phaser; +(function (Phaser) { + var Frame = (function () { + function Frame(x, y, width, height, name) { + // Useful for Texture Atlas files (is set to the filename value) + this.name = ''; + // Rotated? (not yet implemented) + this.rotated = false; + // Either cw or ccw, rotation is always 90 degrees + this.rotationDirection = 'cw'; + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.name = name; + this.rotated = false; + this.trimmed = false; + } + Frame.prototype.setRotation = function (rotated, rotationDirection) { + // Not yet supported + }; + Frame.prototype.setTrim = function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { + this.trimmed = trimmed; + this.sourceSizeW = actualWidth; + this.sourceSizeH = actualHeight; + this.spriteSourceSizeX = destX; + this.spriteSourceSizeY = destY; + this.spriteSourceSizeW = destWidth; + this.spriteSourceSizeH = destHeight; + }; + return Frame; + })(); + Phaser.Frame = Frame; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/animation/FrameData.js b/Phaser/system/animation/FrameData.js new file mode 100644 index 00000000..e50405f2 --- /dev/null +++ b/Phaser/system/animation/FrameData.js @@ -0,0 +1,84 @@ +/// +/** +* Phaser - FrameData +* +* FrameData is a container for Frame objects, the internal representation of animation data in Phaser. +*/ +var Phaser; +(function (Phaser) { + var FrameData = (function () { + function FrameData() { + this._frames = []; + this._frameNames = []; + } + Object.defineProperty(FrameData.prototype, "total", { + get: function () { + return this._frames.length; + }, + enumerable: true, + configurable: true + }); + FrameData.prototype.addFrame = function (frame) { + frame.index = this._frames.length; + this._frames.push(frame); + if(frame.name !== '') { + this._frameNames[frame.name] = frame.index; + } + return frame; + }; + FrameData.prototype.getFrame = function (index) { + if(this._frames[index]) { + return this._frames[index]; + } + return null; + }; + FrameData.prototype.getFrameByName = function (name) { + if(this._frameNames[name] >= 0) { + return this._frames[this._frameNames[name]]; + } + return null; + }; + FrameData.prototype.checkFrameName = function (name) { + if(this._frameNames[name] >= 0) { + return true; + } + return false; + }; + FrameData.prototype.getFrameRange = function (start, end, output) { + if (typeof output === "undefined") { output = []; } + for(var i = start; i <= end; i++) { + output.push(this._frames[i]); + } + return output; + }; + FrameData.prototype.getFrameIndexes = function (output) { + if (typeof output === "undefined") { output = []; } + output.length = 0; + for(var i = 0; i < this._frames.length; i++) { + output.push(i); + } + return output; + }; + FrameData.prototype.getFrameIndexesByName = function (input) { + var output = []; + for(var i = 0; i < input.length; i++) { + if(this.getFrameByName(input[i])) { + output.push(this.getFrameByName(input[i]).index); + } + } + return output; + }; + FrameData.prototype.getAllFrames = function () { + return this._frames; + }; + FrameData.prototype.getFrames = function (range) { + var output = []; + for(var i = 0; i < range.length; i++) { + output.push(this._frames[i]); + } + return output; + }; + return FrameData; + })(); + Phaser.FrameData = FrameData; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Back.js b/Phaser/system/easing/Back.js new file mode 100644 index 00000000..5ed554f4 --- /dev/null +++ b/Phaser/system/easing/Back.js @@ -0,0 +1,32 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Back + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Back = (function () { + function Back() { } + Back.In = function In(k) { + var s = 1.70158; + return k * k * ((s + 1) * k - s); + }; + Back.Out = function Out(k) { + var s = 1.70158; + return --k * k * ((s + 1) * k + s) + 1; + }; + Back.InOut = function InOut(k) { + var s = 1.70158 * 1.525; + if((k *= 2) < 1) { + return 0.5 * (k * k * ((s + 1) * k - s)); + } + return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); + }; + return Back; + })(); + Easing.Back = Back; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Bounce.js b/Phaser/system/easing/Bounce.js new file mode 100644 index 00000000..561e4e21 --- /dev/null +++ b/Phaser/system/easing/Bounce.js @@ -0,0 +1,37 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Bounce + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Bounce = (function () { + function Bounce() { } + Bounce.In = function In(k) { + return 1 - Phaser.Easing.Bounce.Out(1 - k); + }; + Bounce.Out = function Out(k) { + if(k < (1 / 2.75)) { + return 7.5625 * k * k; + } else if(k < (2 / 2.75)) { + return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; + } else if(k < (2.5 / 2.75)) { + return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; + } else { + return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; + } + }; + Bounce.InOut = function InOut(k) { + if(k < 0.5) { + return Phaser.Easing.Bounce.In(k * 2) * 0.5; + } + return Phaser.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5; + }; + return Bounce; + })(); + Easing.Bounce = Bounce; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Circular.js b/Phaser/system/easing/Circular.js new file mode 100644 index 00000000..7b8e3f2b --- /dev/null +++ b/Phaser/system/easing/Circular.js @@ -0,0 +1,29 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Circular + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Circular = (function () { + function Circular() { } + Circular.In = function In(k) { + return 1 - Math.sqrt(1 - k * k); + }; + Circular.Out = function Out(k) { + return Math.sqrt(1 - (--k * k)); + }; + Circular.InOut = function InOut(k) { + if((k *= 2) < 1) { + return -0.5 * (Math.sqrt(1 - k * k) - 1); + } + return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); + }; + return Circular; + })(); + Easing.Circular = Circular; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Cubic.js b/Phaser/system/easing/Cubic.js new file mode 100644 index 00000000..d97ddd50 --- /dev/null +++ b/Phaser/system/easing/Cubic.js @@ -0,0 +1,29 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Cubic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Cubic = (function () { + function Cubic() { } + Cubic.In = function In(k) { + return k * k * k; + }; + Cubic.Out = function Out(k) { + return --k * k * k + 1; + }; + Cubic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k; + } + return 0.5 * ((k -= 2) * k * k + 2); + }; + return Cubic; + })(); + Easing.Cubic = Cubic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Elastic.js b/Phaser/system/easing/Elastic.js new file mode 100644 index 00000000..cbea20c6 --- /dev/null +++ b/Phaser/system/easing/Elastic.js @@ -0,0 +1,68 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Elastic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Elastic = (function () { + function Elastic() { } + Elastic.In = function In(k) { + var s, a = 0.1, p = 0.4; + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if(!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + }; + Elastic.Out = function Out(k) { + var s, a = 0.1, p = 0.4; + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if(!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); + }; + Elastic.InOut = function InOut(k) { + var s, a = 0.1, p = 0.4; + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if(!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + if((k *= 2) < 1) { + return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + } + return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; + }; + return Elastic; + })(); + Easing.Elastic = Elastic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Exponential.js b/Phaser/system/easing/Exponential.js new file mode 100644 index 00000000..69bfc021 --- /dev/null +++ b/Phaser/system/easing/Exponential.js @@ -0,0 +1,35 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Exponential + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Exponential = (function () { + function Exponential() { } + Exponential.In = function In(k) { + return k === 0 ? 0 : Math.pow(1024, k - 1); + }; + Exponential.Out = function Out(k) { + return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); + }; + Exponential.InOut = function InOut(k) { + if(k === 0) { + return 0; + } + if(k === 1) { + return 1; + } + if((k *= 2) < 1) { + return 0.5 * Math.pow(1024, k - 1); + } + return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); + }; + return Exponential; + })(); + Easing.Exponential = Exponential; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Linear.js b/Phaser/system/easing/Linear.js new file mode 100644 index 00000000..77786660 --- /dev/null +++ b/Phaser/system/easing/Linear.js @@ -0,0 +1,20 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Linear + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Linear = (function () { + function Linear() { } + Linear.None = function None(k) { + return k; + }; + return Linear; + })(); + Easing.Linear = Linear; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Quadratic.js b/Phaser/system/easing/Quadratic.js new file mode 100644 index 00000000..91fe1f3f --- /dev/null +++ b/Phaser/system/easing/Quadratic.js @@ -0,0 +1,29 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quadratic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quadratic = (function () { + function Quadratic() { } + Quadratic.In = function In(k) { + return k * k; + }; + Quadratic.Out = function Out(k) { + return k * (2 - k); + }; + Quadratic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k; + } + return -0.5 * (--k * (k - 2) - 1); + }; + return Quadratic; + })(); + Easing.Quadratic = Quadratic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Quartic.js b/Phaser/system/easing/Quartic.js new file mode 100644 index 00000000..4eb8d42b --- /dev/null +++ b/Phaser/system/easing/Quartic.js @@ -0,0 +1,29 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quartic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quartic = (function () { + function Quartic() { } + Quartic.In = function In(k) { + return k * k * k * k; + }; + Quartic.Out = function Out(k) { + return 1 - (--k * k * k * k); + }; + Quartic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k * k; + } + return -0.5 * ((k -= 2) * k * k * k - 2); + }; + return Quartic; + })(); + Easing.Quartic = Quartic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Quintic.js b/Phaser/system/easing/Quintic.js new file mode 100644 index 00000000..2f7dd072 --- /dev/null +++ b/Phaser/system/easing/Quintic.js @@ -0,0 +1,29 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Quintic + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Quintic = (function () { + function Quintic() { } + Quintic.In = function In(k) { + return k * k * k * k * k; + }; + Quintic.Out = function Out(k) { + return --k * k * k * k * k + 1; + }; + Quintic.InOut = function InOut(k) { + if((k *= 2) < 1) { + return 0.5 * k * k * k * k * k; + } + return 0.5 * ((k -= 2) * k * k * k * k + 2); + }; + return Quintic; + })(); + Easing.Quintic = Quintic; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/easing/Sinusoidal.js b/Phaser/system/easing/Sinusoidal.js new file mode 100644 index 00000000..b6ee96f2 --- /dev/null +++ b/Phaser/system/easing/Sinusoidal.js @@ -0,0 +1,26 @@ +var Phaser; +(function (Phaser) { + /// + /** + * Phaser - Easing - Sinusoidal + * + * For use with Phaser.Tween + */ + (function (Easing) { + var Sinusoidal = (function () { + function Sinusoidal() { } + Sinusoidal.In = function In(k) { + return 1 - Math.cos(k * Math.PI / 2); + }; + Sinusoidal.Out = function Out(k) { + return Math.sin(k * Math.PI / 2); + }; + Sinusoidal.InOut = function InOut(k) { + return 0.5 * (1 - Math.cos(Math.PI * k)); + }; + return Sinusoidal; + })(); + Easing.Sinusoidal = Sinusoidal; + })(Phaser.Easing || (Phaser.Easing = {})); + var Easing = Phaser.Easing; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/input/Finger.js b/Phaser/system/input/Finger.js new file mode 100644 index 00000000..2e39a34d --- /dev/null +++ b/Phaser/system/input/Finger.js @@ -0,0 +1,231 @@ +/// +/** +* Phaser - Finger +* +* A Finger object is used by the Touch manager and represents a single finger on the touch screen. +*/ +var Phaser; +(function (Phaser) { + var Finger = (function () { + /** + * Constructor + * @param {Phaser.Game} game. + * @return {Phaser.Finger} This object. + */ + function Finger(game) { + /** + * + * @property point + * @type Point + **/ + this.point = null; + /** + * + * @property circle + * @type Circle + **/ + this.circle = null; + /** + * + * @property withinGame + * @type Boolean + */ + this.withinGame = false; + /** + * The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset + * @property clientX + * @type Number + */ + this.clientX = -1; + // + /** + * The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset + * @property clientY + * @type Number + */ + this.clientY = -1; + // + /** + * The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset + * @property pageX + * @type Number + */ + this.pageX = -1; + /** + * The vertical coordinate of point relative to the viewport in pixels, including any scroll offset + * @property pageY + * @type Number + */ + this.pageY = -1; + /** + * The horizontal coordinate of point relative to the screen in pixels + * @property screenX + * @type Number + */ + this.screenX = -1; + /** + * The vertical coordinate of point relative to the screen in pixels + * @property screenY + * @type Number + */ + this.screenY = -1; + /** + * The horizontal coordinate of point relative to the game element + * @property x + * @type Number + */ + this.x = -1; + /** + * The vertical coordinate of point relative to the game element + * @property y + * @type Number + */ + this.y = -1; + /** + * + * @property isDown + * @type Boolean + **/ + this.isDown = false; + /** + * + * @property isUp + * @type Boolean + **/ + this.isUp = false; + /** + * + * @property timeDown + * @type Number + **/ + this.timeDown = 0; + /** + * + * @property duration + * @type Number + **/ + this.duration = 0; + /** + * + * @property timeUp + * @type Number + **/ + this.timeUp = 0; + /** + * + * @property justPressedRate + * @type Number + **/ + this.justPressedRate = 200; + /** + * + * @property justReleasedRate + * @type Number + **/ + this.justReleasedRate = 200; + this._game = game; + this.active = false; + } + Finger.prototype.start = /** + * + * @method start + * @param {Any} event + */ + function (event) { + this.identifier = event.identifier; + this.target = event.target; + // populate geom objects + if(this.point === null) { + this.point = new Phaser.Point(); + } + if(this.circle === null) { + this.circle = new Phaser.Circle(0, 0, 44); + } + this.move(event); + this.active = true; + this.withinGame = true; + this.isDown = true; + this.isUp = false; + this.timeDown = this._game.time.now; + }; + Finger.prototype.move = /** + * + * @method move + * @param {Any} event + */ + function (event) { + this.clientX = event.clientX; + this.clientY = event.clientY; + this.pageX = event.pageX; + this.pageY = event.pageY; + this.screenX = event.screenX; + this.screenY = event.screenY; + this.x = this.pageX - this._game.stage.offset.x; + this.y = this.pageY - this._game.stage.offset.y; + this.point.setTo(this.x, this.y); + this.circle.setTo(this.x, this.y, 44); + // Droppings history (used for gestures and motion tracking) + this.duration = this._game.time.now - this.timeDown; + }; + Finger.prototype.leave = /** + * + * @method leave + * @param {Any} event + */ + function (event) { + this.withinGame = false; + this.move(event); + }; + Finger.prototype.stop = /** + * + * @method stop + * @param {Any} event + */ + function (event) { + this.active = false; + this.withinGame = false; + this.isDown = false; + this.isUp = true; + this.timeUp = this._game.time.now; + this.duration = this.timeUp - this.timeDown; + }; + Finger.prototype.justPressed = /** + * + * @method justPressed + * @param {Number} [duration]. + * @return {Boolean} + */ + function (duration) { + if (typeof duration === "undefined") { duration = this.justPressedRate; } + if(this.isDown === true && (this.timeDown + duration) > this._game.time.now) { + return true; + } else { + return false; + } + }; + Finger.prototype.justReleased = /** + * + * @method justReleased + * @param {Number} [duration]. + * @return {Boolean} + */ + function (duration) { + if (typeof duration === "undefined") { duration = this.justReleasedRate; } + if(this.isUp === true && (this.timeUp + duration) > this._game.time.now) { + return true; + } else { + return false; + } + }; + Finger.prototype.toString = /** + * Returns a string representation of this object. + * @method toString + * @return {string} a string representation of the instance. + **/ + function () { + return "[{Finger (identifer=" + this.identifier + " active=" + this.active + " duration=" + this.duration + " withinGame=" + this.withinGame + " x=" + this.x + " y=" + this.y + " clientX=" + this.clientX + " clientY=" + this.clientY + " screenX=" + this.screenX + " screenY=" + this.screenY + " pageX=" + this.pageX + " pageY=" + this.pageY + ")}]"; + }; + return Finger; + })(); + Phaser.Finger = Finger; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/input/Input.js b/Phaser/system/input/Input.js new file mode 100644 index 00000000..836e5b1b --- /dev/null +++ b/Phaser/system/input/Input.js @@ -0,0 +1,58 @@ +/// +/// +/** +* Phaser - Input +* +* A game specific Input manager that looks after the mouse, keyboard and touch objects. This is updated by the core game loop. +*/ +var Phaser; +(function (Phaser) { + var Input = (function () { + function Input(game) { + this.x = 0; + this.y = 0; + this.scaleX = 1; + this.scaleY = 1; + this.worldX = 0; + this.worldY = 0; + this._game = game; + this.mouse = new Phaser.Mouse(this._game); + this.keyboard = new Phaser.Keyboard(this._game); + this.touch = new Phaser.Touch(this._game); + this.onDown = new Phaser.Signal(); + this.onUp = new Phaser.Signal(); + } + Input.prototype.update = function () { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.worldX = this._game.camera.worldView.x + this.x; + this.worldY = this._game.camera.worldView.y + this.y; + this.mouse.update(); + this.touch.update(); + }; + Input.prototype.reset = function () { + this.mouse.reset(); + this.keyboard.reset(); + this.touch.reset(); + }; + Input.prototype.getWorldX = function (camera) { + if (typeof camera === "undefined") { camera = this._game.camera; } + return camera.worldView.x + this.x; + }; + Input.prototype.getWorldY = function (camera) { + if (typeof camera === "undefined") { camera = this._game.camera; } + return camera.worldView.y + this.y; + }; + Input.prototype.renderDebugInfo = function (x, y, color) { + if (typeof color === "undefined") { color = 'rgb(255,255,255)'; } + this._game.stage.context.font = '14px Courier'; + this._game.stage.context.fillStyle = color; + this._game.stage.context.fillText('Input', x, y); + this._game.stage.context.fillText('Screen X: ' + this.x + ' Screen Y: ' + this.y, x, y + 14); + this._game.stage.context.fillText('World X: ' + this.worldX + ' World Y: ' + this.worldY, x, y + 28); + this._game.stage.context.fillText('Scale X: ' + this.scaleX.toFixed(1) + ' Scale Y: ' + this.scaleY.toFixed(1), x, y + 42); + }; + return Input; + })(); + Phaser.Input = Input; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/input/Keyboard.js b/Phaser/system/input/Keyboard.js new file mode 100644 index 00000000..2e515718 --- /dev/null +++ b/Phaser/system/input/Keyboard.js @@ -0,0 +1,204 @@ +/// +/** +* Phaser - Keyboard +* +* The Keyboard class handles keyboard interactions with the game and the resulting events. +* The avoid stealing all browser input we don't use event.preventDefault. If you would like to trap a specific key however +* then use the addKeyCapture() method. +*/ +var Phaser; +(function (Phaser) { + var Keyboard = (function () { + function Keyboard(game) { + this._keys = { + }; + this._capture = { + }; + this._game = game; + this.start(); + } + Keyboard.prototype.start = function () { + var _this = this; + document.body.addEventListener('keydown', function (event) { + return _this.onKeyDown(event); + }, false); + document.body.addEventListener('keyup', function (event) { + return _this.onKeyUp(event); + }, false); + }; + Keyboard.prototype.addKeyCapture = function (keycode) { + if(typeof keycode === 'object') { + for(var i = 0; i < keycode.length; i++) { + this._capture[keycode[i]] = true; + } + } else { + this._capture[keycode] = true; + } + }; + Keyboard.prototype.removeKeyCapture = function (keycode) { + delete this._capture[keycode]; + }; + Keyboard.prototype.clearCaptures = function () { + this._capture = { + }; + }; + Keyboard.prototype.onKeyDown = function (event) { + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: true, + timeDown: this._game.time.now, + timeUp: 0 + }; + } else { + this._keys[event.keyCode].isDown = true; + this._keys[event.keyCode].timeDown = this._game.time.now; + } + }; + Keyboard.prototype.onKeyUp = function (event) { + if(this._capture[event.keyCode]) { + event.preventDefault(); + } + if(!this._keys[event.keyCode]) { + this._keys[event.keyCode] = { + isDown: false, + timeDown: 0, + timeUp: this._game.time.now + }; + } else { + this._keys[event.keyCode].isDown = false; + this._keys[event.keyCode].timeUp = this._game.time.now; + } + }; + Keyboard.prototype.reset = function () { + for(var key in this._keys) { + this._keys[key].isDown = false; + } + }; + Keyboard.prototype.justPressed = function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === true && (this._game.time.now - this._keys[keycode].timeDown < duration)) { + return true; + } else { + return false; + } + }; + Keyboard.prototype.justReleased = function (keycode, duration) { + if (typeof duration === "undefined") { duration = 250; } + if(this._keys[keycode] && this._keys[keycode].isDown === false && (this._game.time.now - this._keys[keycode].timeUp < duration)) { + return true; + } else { + return false; + } + }; + Keyboard.prototype.isDown = function (keycode) { + if(this._keys[keycode]) { + return this._keys[keycode].isDown; + } else { + return false; + } + }; + Keyboard.A = "A".charCodeAt(0); + Keyboard.B = "B".charCodeAt(0); + Keyboard.C = "C".charCodeAt(0); + Keyboard.D = "D".charCodeAt(0); + Keyboard.E = "E".charCodeAt(0); + Keyboard.F = "F".charCodeAt(0); + Keyboard.G = "G".charCodeAt(0); + Keyboard.H = "H".charCodeAt(0); + Keyboard.I = "I".charCodeAt(0); + Keyboard.J = "J".charCodeAt(0); + Keyboard.K = "K".charCodeAt(0); + Keyboard.L = "L".charCodeAt(0); + Keyboard.M = "M".charCodeAt(0); + Keyboard.N = "N".charCodeAt(0); + Keyboard.O = "O".charCodeAt(0); + Keyboard.P = "P".charCodeAt(0); + Keyboard.Q = "Q".charCodeAt(0); + Keyboard.R = "R".charCodeAt(0); + Keyboard.S = "S".charCodeAt(0); + Keyboard.T = "T".charCodeAt(0); + Keyboard.U = "U".charCodeAt(0); + Keyboard.V = "V".charCodeAt(0); + Keyboard.W = "W".charCodeAt(0); + Keyboard.X = "X".charCodeAt(0); + Keyboard.Y = "Y".charCodeAt(0); + Keyboard.Z = "Z".charCodeAt(0); + Keyboard.ZERO = "0".charCodeAt(0); + Keyboard.ONE = "1".charCodeAt(0); + Keyboard.TWO = "2".charCodeAt(0); + Keyboard.THREE = "3".charCodeAt(0); + Keyboard.FOUR = "4".charCodeAt(0); + Keyboard.FIVE = "5".charCodeAt(0); + Keyboard.SIX = "6".charCodeAt(0); + Keyboard.SEVEN = "7".charCodeAt(0); + Keyboard.EIGHT = "8".charCodeAt(0); + Keyboard.NINE = "9".charCodeAt(0); + Keyboard.NUMPAD_0 = 96; + Keyboard.NUMPAD_1 = 97; + Keyboard.NUMPAD_2 = 98; + Keyboard.NUMPAD_3 = 99; + Keyboard.NUMPAD_4 = 100; + Keyboard.NUMPAD_5 = 101; + Keyboard.NUMPAD_6 = 102; + Keyboard.NUMPAD_7 = 103; + Keyboard.NUMPAD_8 = 104; + Keyboard.NUMPAD_9 = 105; + Keyboard.NUMPAD_MULTIPLY = 106; + Keyboard.NUMPAD_ADD = 107; + Keyboard.NUMPAD_ENTER = 108; + Keyboard.NUMPAD_SUBTRACT = 109; + Keyboard.NUMPAD_DECIMAL = 110; + Keyboard.NUMPAD_DIVIDE = 111; + Keyboard.F1 = 112; + Keyboard.F2 = 113; + Keyboard.F3 = 114; + Keyboard.F4 = 115; + Keyboard.F5 = 116; + Keyboard.F6 = 117; + Keyboard.F7 = 118; + Keyboard.F8 = 119; + Keyboard.F9 = 120; + Keyboard.F10 = 121; + Keyboard.F11 = 122; + Keyboard.F12 = 123; + Keyboard.F13 = 124; + Keyboard.F14 = 125; + Keyboard.F15 = 126; + Keyboard.COLON = 186; + Keyboard.EQUALS = 187; + Keyboard.UNDERSCORE = 189; + Keyboard.QUESTION_MARK = 191; + Keyboard.TILDE = 192; + Keyboard.OPEN_BRACKET = 219; + Keyboard.BACKWARD_SLASH = 220; + Keyboard.CLOSED_BRACKET = 221; + Keyboard.QUOTES = 222; + Keyboard.BACKSPACE = 8; + Keyboard.TAB = 9; + Keyboard.CLEAR = 12; + Keyboard.ENTER = 13; + Keyboard.SHIFT = 16; + Keyboard.CONTROL = 17; + Keyboard.ALT = 18; + Keyboard.CAPS_LOCK = 20; + Keyboard.ESC = 27; + Keyboard.SPACEBAR = 32; + Keyboard.PAGE_UP = 33; + Keyboard.PAGE_DOWN = 34; + Keyboard.END = 35; + Keyboard.HOME = 36; + Keyboard.LEFT = 37; + Keyboard.UP = 38; + Keyboard.RIGHT = 39; + Keyboard.DOWN = 40; + Keyboard.INSERT = 45; + Keyboard.DELETE = 46; + Keyboard.HELP = 47; + Keyboard.NUM_LOCK = 144; + return Keyboard; + })(); + Phaser.Keyboard = Keyboard; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/input/Mouse.js b/Phaser/system/input/Mouse.js new file mode 100644 index 00000000..9d0a4278 --- /dev/null +++ b/Phaser/system/input/Mouse.js @@ -0,0 +1,80 @@ +/// +/** +* Phaser - Mouse +* +* The Mouse class handles mouse interactions with the game and the resulting events. +*/ +var Phaser; +(function (Phaser) { + var Mouse = (function () { + function Mouse(game) { + this._x = 0; + this._y = 0; + this.isDown = false; + this.isUp = true; + this.timeDown = 0; + this.duration = 0; + this.timeUp = 0; + this._game = game; + this.start(); + } + Mouse.LEFT_BUTTON = 0; + Mouse.MIDDLE_BUTTON = 1; + Mouse.RIGHT_BUTTON = 2; + Mouse.prototype.start = function () { + var _this = this; + this._game.stage.canvas.addEventListener('mousedown', function (event) { + return _this.onMouseDown(event); + }, true); + this._game.stage.canvas.addEventListener('mousemove', function (event) { + return _this.onMouseMove(event); + }, true); + this._game.stage.canvas.addEventListener('mouseup', function (event) { + return _this.onMouseUp(event); + }, true); + }; + Mouse.prototype.reset = function () { + this.isDown = false; + this.isUp = true; + }; + Mouse.prototype.onMouseDown = function (event) { + this.button = event.button; + this._x = event.clientX - this._game.stage.x; + this._y = event.clientY - this._game.stage.y; + this._game.input.x = this._x * this._game.input.scaleX; + this._game.input.y = this._y * this._game.input.scaleY; + this.isDown = true; + this.isUp = false; + this.timeDown = this._game.time.now; + this._game.input.onDown.dispatch(this._game.input.x, this._game.input.y, this.timeDown); + }; + Mouse.prototype.update = function () { + //this._game.input.x = this._x * this._game.input.scaleX; + //this._game.input.y = this._y * this._game.input.scaleY; + if(this.isDown) { + this.duration = this._game.time.now - this.timeDown; + } + }; + Mouse.prototype.onMouseMove = function (event) { + this.button = event.button; + this._x = event.clientX - this._game.stage.x; + this._y = event.clientY - this._game.stage.y; + this._game.input.x = this._x * this._game.input.scaleX; + this._game.input.y = this._y * this._game.input.scaleY; + }; + Mouse.prototype.onMouseUp = function (event) { + this.button = event.button; + this.isDown = false; + this.isUp = true; + this.timeUp = this._game.time.now; + this.duration = this.timeUp - this.timeDown; + this._x = event.clientX - this._game.stage.x; + this._y = event.clientY - this._game.stage.y; + this._game.input.x = this._x * this._game.input.scaleX; + this._game.input.y = this._y * this._game.input.scaleY; + this._game.input.onUp.dispatch(this._game.input.x, this._game.input.y, this.timeDown); + }; + return Mouse; + })(); + Phaser.Mouse = Mouse; +})(Phaser || (Phaser = {})); diff --git a/Phaser/system/input/Touch.js b/Phaser/system/input/Touch.js new file mode 100644 index 00000000..1f3dce1b --- /dev/null +++ b/Phaser/system/input/Touch.js @@ -0,0 +1,303 @@ +/// +/// +/** +* Phaser - Touch +* +* The Touch class handles touch interactions with the game and the resulting Finger objects. +* http://www.w3.org/TR/touch-events/ +* https://developer.mozilla.org/en-US/docs/DOM/TouchList +* http://www.html5rocks.com/en/mobile/touchandmouse/ +* Note: Android 2.x only supports 1 touch event at once, no multi-touch +* +* @todo Try and resolve update lag in Chrome/Android +* Gestures (pinch, zoom, swipe) +* GameObject Touch +* Touch point within GameObject +* Input Zones (mouse and touch) - lock entities within them + axis aligned drags +*/ +var Phaser; +(function (Phaser) { + var Touch = (function () { + /** + * Constructor + * @param {Game} game. + * @return {Touch} This object. + */ + function Touch(game) { + /** + * + * @property x + * @type Number + **/ + this.x = 0; + /** + * + * @property y + * @type Number + **/ + this.y = 0; + /** + * + * @property isDown + * @type Boolean + **/ + this.isDown = false; + /** + * + * @property isUp + * @type Boolean + **/ + this.isUp = true; + this._game = game; + this.finger1 = new Phaser.Finger(this._game); + this.finger2 = new Phaser.Finger(this._game); + this.finger3 = new Phaser.Finger(this._game); + this.finger4 = new Phaser.Finger(this._game); + this.finger5 = new Phaser.Finger(this._game); + this.finger6 = new Phaser.Finger(this._game); + this.finger7 = new Phaser.Finger(this._game); + this.finger8 = new Phaser.Finger(this._game); + this.finger9 = new Phaser.Finger(this._game); + this.finger10 = new Phaser.Finger(this._game); + this._fingers = [ + this.finger1, + this.finger2, + this.finger3, + this.finger4, + this.finger5, + this.finger6, + this.finger7, + this.finger8, + this.finger9, + this.finger10 + ]; + this.touchDown = new Phaser.Signal(); + this.touchUp = new Phaser.Signal(); + this.start(); + } + Touch.prototype.start = /** + * + * @method start + */ + function () { + var _this = this; + this._game.stage.canvas.addEventListener('touchstart', function (event) { + return _this.onTouchStart(event); + }, false); + this._game.stage.canvas.addEventListener('touchmove', function (event) { + return _this.onTouchMove(event); + }, false); + this._game.stage.canvas.addEventListener('touchend', function (event) { + return _this.onTouchEnd(event); + }, false); + this._game.stage.canvas.addEventListener('touchenter', function (event) { + return _this.onTouchEnter(event); + }, false); + this._game.stage.canvas.addEventListener('touchleave', function (event) { + return _this.onTouchLeave(event); + }, false); + this._game.stage.canvas.addEventListener('touchcancel', function (event) { + return _this.onTouchCancel(event); + }, false); + document.addEventListener('touchmove', function (event) { + return _this.consumeTouchMove(event); + }, false); + }; + Touch.prototype.consumeTouchMove = /** + * Prevent iOS bounce-back (doesn't work?) + * @method consumeTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + }; + Touch.prototype.onTouchStart = /** + * + * @method onTouchStart + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // A list of all the touch points that BECAME active with the current event + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].active === false) { + this._fingers[f].start(event.changedTouches[i]); + this.x = this._fingers[f].x; + this.y = this._fingers[f].y; + this._game.input.x = this.x * this._game.input.scaleX; + this._game.input.y = this.y * this._game.input.scaleY; + this.touchDown.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration); + this._game.input.onDown.dispatch(this._game.input.x, this._game.input.y, this._fingers[f].timeDown); + this.isDown = true; + this.isUp = false; + break; + } + } + } + }; + Touch.prototype.onTouchCancel = /** + * Doesn't appear to be supported by most browsers yet + * @method onTouchCancel + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) + // http://www.w3.org/TR/touch-events/#dfn-touchcancel + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].identifier === event.changedTouches[i].identifier) { + this._fingers[f].stop(event.changedTouches[i]); + break; + } + } + } + }; + Touch.prototype.onTouchEnter = /** + * Doesn't appear to be supported by most browsers yet + * @method onTouchEnter + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // For touch enter and leave its a list of the touch points that have entered or left the target + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].active === false) { + this._fingers[f].start(event.changedTouches[i]); + break; + } + } + } + }; + Touch.prototype.onTouchLeave = /** + * Doesn't appear to be supported by most browsers yet + * @method onTouchLeave + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // For touch enter and leave its a list of the touch points that have entered or left the target + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].identifier === event.changedTouches[i].identifier) { + this._fingers[f].leave(event.changedTouches[i]); + break; + } + } + } + }; + Touch.prototype.onTouchMove = /** + * + * @method onTouchMove + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) + // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].identifier === event.changedTouches[i].identifier) { + this._fingers[f].move(event.changedTouches[i]); + this.x = this._fingers[f].x; + this.y = this._fingers[f].y; + this._game.input.x = this.x * this._game.input.scaleX; + this._game.input.y = this.y * this._game.input.scaleY; + break; + } + } + } + }; + Touch.prototype.onTouchEnd = /** + * + * @method onTouchEnd + * @param {Any} event + **/ + function (event) { + event.preventDefault(); + // For touch end its a list of the touch points that have been removed from the surface + // https://developer.mozilla.org/en-US/docs/DOM/TouchList + // event.changedTouches = the touches that CHANGED in this event, not the total number of them + for(var i = 0; i < event.changedTouches.length; i++) { + for(var f = 0; f < this._fingers.length; f++) { + if(this._fingers[f].identifier === event.changedTouches[i].identifier) { + this._fingers[f].stop(event.changedTouches[i]); + this.x = this._fingers[f].x; + this.y = this._fingers[f].y; + this._game.input.x = this.x * this._game.input.scaleX; + this._game.input.y = this.y * this._game.input.scaleY; + this.touchUp.dispatch(this._fingers[f].x, this._fingers[f].y, this._fingers[f].timeDown, this._fingers[f].timeUp, this._fingers[f].duration); + this._game.input.onUp.dispatch(this._game.input.x, this._game.input.y, this._fingers[f].timeUp); + this.isDown = false; + this.isUp = true; + break; + } + } + } + }; + Touch.prototype.calculateDistance = /** + * + * @method calculateDistance + * @param {Finger} finger1 + * @param {Finger} finger2 + **/ + function (finger1, finger2) { + }; + Touch.prototype.calculateAngle = /** + * + * @method calculateAngle + * @param {Finger} finger1 + * @param {Finger} finger2 + **/ + function (finger1, finger2) { + }; + Touch.prototype.checkOverlap = /** + * + * @method checkOverlap + * @param {Finger} finger1 + * @param {Finger} finger2 + **/ + function (finger1, finger2) { + }; + Touch.prototype.update = /** + * + * @method update + */ + function () { + }; + Touch.prototype.stop = /** + * + * @method stop + */ + function () { + //this._domElement.addEventListener('touchstart', (event) => this.onTouchStart(event), false); + //this._domElement.addEventListener('touchmove', (event) => this.onTouchMove(event), false); + //this._domElement.addEventListener('touchend', (event) => this.onTouchEnd(event), false); + //this._domElement.addEventListener('touchenter', (event) => this.onTouchEnter(event), false); + //this._domElement.addEventListener('touchleave', (event) => this.onTouchLeave(event), false); + //this._domElement.addEventListener('touchcancel', (event) => this.onTouchCancel(event), false); + }; + Touch.prototype.reset = /** + * + * @method reset + **/ + function () { + this.isDown = false; + this.isUp = false; + }; + return Touch; + })(); + Phaser.Touch = Touch; +})(Phaser || (Phaser = {})); diff --git a/Phaser/tweens/easing/Back.ts b/Phaser/tweens/easing/Back.ts index b09da666..f08ed2c7 100644 --- a/Phaser/tweens/easing/Back.ts +++ b/Phaser/tweens/easing/Back.ts @@ -1,15 +1,28 @@ /// /** -* Phaser - Easing - Back -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Back easing methods. + * + * @class Back + */ export class Back { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { var s = 1.70158; @@ -17,6 +30,13 @@ module Phaser.Easing { } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { var s = 1.70158; @@ -24,6 +44,13 @@ module Phaser.Easing { } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { var s = 1.70158 * 1.525; diff --git a/Phaser/tweens/easing/Bounce.ts b/Phaser/tweens/easing/Bounce.ts index d5eefe35..8391f01d 100644 --- a/Phaser/tweens/easing/Bounce.ts +++ b/Phaser/tweens/easing/Bounce.ts @@ -1,21 +1,41 @@ /// /** -* Phaser - Easing - Bounce -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Bounce easing methods. + * + * @class Bounce + */ export class Bounce { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return 1 - Phaser.Easing.Bounce.Out(1 - k); } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { if (k < (1 / 2.75)) @@ -37,6 +57,13 @@ module Phaser.Easing { } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if (k < 0.5) return Phaser.Easing.Bounce.In(k * 2) * 0.5; diff --git a/Phaser/tweens/easing/Cubic.ts b/Phaser/tweens/easing/Cubic.ts index c3e319d1..5ce27eaa 100644 --- a/Phaser/tweens/easing/Cubic.ts +++ b/Phaser/tweens/easing/Cubic.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Cubic -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Cubic easing methods. + * + * @class Cubic + */ export class Cubic { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return k * k * k; } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return --k * k * k + 1; } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if ((k *= 2) < 1) return 0.5 * k * k * k; diff --git a/Phaser/tweens/easing/Elastic.ts b/Phaser/tweens/easing/Elastic.ts index 73cbb13e..0f8d3889 100644 --- a/Phaser/tweens/easing/Elastic.ts +++ b/Phaser/tweens/easing/Elastic.ts @@ -1,15 +1,28 @@ /// /** -* Phaser - Easing - Elastic -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Elastic easing methods. + * + * @class Elastic + */ export class Elastic { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { var s, a = 0.1, p = 0.4; @@ -21,6 +34,13 @@ module Phaser.Easing { } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { var s, a = 0.1, p = 0.4; @@ -32,6 +52,13 @@ module Phaser.Easing { } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { var s, a = 0.1, p = 0.4; diff --git a/Phaser/tweens/easing/Exponential.ts b/Phaser/tweens/easing/Exponential.ts index c0acb811..60f50908 100644 --- a/Phaser/tweens/easing/Exponential.ts +++ b/Phaser/tweens/easing/Exponential.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Exponential -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Exponential easing methods. + * + * @class Exponential + */ export class Exponential { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return k === 0 ? 0 : Math.pow(1024, k - 1); } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if (k === 0) return 0; diff --git a/Phaser/tweens/easing/Linear.ts b/Phaser/tweens/easing/Linear.ts index 0e8a6359..5e40abbb 100644 --- a/Phaser/tweens/easing/Linear.ts +++ b/Phaser/tweens/easing/Linear.ts @@ -1,15 +1,28 @@ /// /** -* Phaser - Easing - Linear -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Linear easing methods. + * + * @class Linear + */ export class Linear { + /** + * A Linear Ease only has a None method. + * + * @method None + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static None(k) { return k; diff --git a/Phaser/tweens/easing/Quadratic.ts b/Phaser/tweens/easing/Quadratic.ts index 24b0959c..e5ccaa83 100644 --- a/Phaser/tweens/easing/Quadratic.ts +++ b/Phaser/tweens/easing/Quadratic.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Quadratic -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Quadratic easing methods. + * + * @class Quadratic + */ export class Quadratic { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return k * k; } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return k * (2 - k); } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if ((k *= 2) < 1) return 0.5 * k * k; diff --git a/Phaser/tweens/easing/Quartic.ts b/Phaser/tweens/easing/Quartic.ts index f5f1b6b8..008cd073 100644 --- a/Phaser/tweens/easing/Quartic.ts +++ b/Phaser/tweens/easing/Quartic.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Quartic -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Quartic easing methods. + * + * @class Quartic + */ export class Quartic { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return k * k * k * k; } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return 1 - (--k * k * k * k); } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if ((k *= 2) < 1) return 0.5 * k * k * k * k; diff --git a/Phaser/tweens/easing/Quintic.ts b/Phaser/tweens/easing/Quintic.ts index dc4f0066..03a95108 100644 --- a/Phaser/tweens/easing/Quintic.ts +++ b/Phaser/tweens/easing/Quintic.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Quintic -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Quintic easing methods. + * + * @class Quintic + */ export class Quintic { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return k * k * k * k * k; } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return --k * k * k * k * k + 1; } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { if ((k *= 2) < 1) return 0.5 * k * k * k * k * k; diff --git a/Phaser/tweens/easing/Sinusoidal.ts b/Phaser/tweens/easing/Sinusoidal.ts index b73ad3c4..fe52017e 100644 --- a/Phaser/tweens/easing/Sinusoidal.ts +++ b/Phaser/tweens/easing/Sinusoidal.ts @@ -1,27 +1,54 @@ /// /** -* Phaser - Easing - Sinusoidal -* -* For use with Phaser.Tween +* @author Richard Davey +* @author sole (http://soledadpenades.com), tween.js +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser.Easing { + /** + * Sinusoidal easing methods. + * + * @class Sinusoidal + */ export class Sinusoidal { + /** + * The In ease method. + * + * @method In + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static In(k) { return 1 - Math.cos(k * Math.PI / 2); } + /** + * The Out ease method. + * + * @method Out + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static Out(k) { return Math.sin(k * Math.PI / 2); } + /** + * The InOut ease method. + * + * @method InOut + * @param {Number} k The value to ease. + * @return {Number} The eased value. + */ public static InOut(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); diff --git a/Phaser/utils/CanvasUtils.ts b/Phaser/utils/CanvasUtils.ts index a2218053..6ae96d4d 100644 --- a/Phaser/utils/CanvasUtils.ts +++ b/Phaser/utils/CanvasUtils.ts @@ -1,19 +1,39 @@ /// /** -* Phaser - CanvasUtils -* -* A collection of methods useful for manipulating canvas objects. +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating canvas objects. + * + * @class CanvasUtils + */ export class CanvasUtils { + /** + * Returns the aspect ratio of the given canvas. + * + * @method getAspectRatio + * @param {HTMLCanvasElement} canvas The canvas to get the aspect ratio from. + * @return {Number} Returns true on success + */ public static getAspectRatio(canvas: HTMLCanvasElement): number { return canvas.width / canvas.height; } + /** + * Sets the background color behind the canvas. This changes the canvas style property. + * + * @method setBackgroundColor + * @param {HTMLCanvasElement} canvas The canvas to set the background color on. + * @param {String} color The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. + * @return {HTMLCanvasElement} Returns the source canvas. + */ public static setBackgroundColor(canvas: HTMLCanvasElement, color: string = 'rgb(0,0,0)'): HTMLCanvasElement { canvas.style.backgroundColor = color; @@ -21,6 +41,14 @@ module Phaser { } + /** + * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. + * + * @method setTouchAction + * @param {HTMLCanvasElement} canvas The canvas to set the touch action on. + * @param {String} value The touch action to set. Defaults to 'none'. + * @return {HTMLCanvasElement} Returns the source canvas. + */ public static setTouchAction(canvas: HTMLCanvasElement, value: string= 'none'): HTMLCanvasElement { canvas.style.msTouchAction = value; @@ -31,6 +59,16 @@ module Phaser { } + /** + * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. + * If no parent is given it will be added as a child of the document.body. + * + * @method addToDOM + * @param {HTMLCanvasElement} canvas The canvas to set the touch action on. + * @param {String} parent The DOM element to add the canvas to. Defaults to ''. + * @param {Boolean} overflowHidden If set to true it will add the overflow='hidden' style to the parent DOM element. + * @return {HTMLCanvasElement} Returns the source canvas. + */ public static addToDOM(canvas: HTMLCanvasElement, parent: string = '', overflowHidden: boolean = true): HTMLCanvasElement { if ((parent !== '' || parent !== null) && document.getElementById(parent)) @@ -51,6 +89,19 @@ module Phaser { } + /** + * Sets the transform of the given canvas to the matrix values provided. + * + * @method setTransform + * @param {CanvasRenderingContext2D} context The context to set the transform on. + * @param {Number} translateX The value to translate horizontally by. + * @param {Number} translateY The value to translate vertically by. + * @param {Number} scaleX The value to scale horizontally by. + * @param {Number} scaleY The value to scale vertically by. + * @param {Number} skewX The value to skew horizontaly by. + * @param {Number} skewY The value to skew vertically by. + * @return {CanvasRenderingContext2D} Returns the source context. + */ public static setTransform(context: CanvasRenderingContext2D, translateX: number, translateY: number, scaleX: number, scaleY: number, skewX: number, skewY: number): CanvasRenderingContext2D { context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); @@ -59,6 +110,18 @@ module Phaser { } + /** + * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. + * By default browsers have image smoothing enabled, which isn't always what you visually want, especially + * when using pixel art in a game. Note that this sets the property on the context itself, so that any image + * drawn to the context will be affected. This sets the property across all current browsers but support is + * patchy on earlier browsers, especially on mobile. + * + * @method setSmoothingEnabled + * @param {CanvasRenderingContext2D} context The context to enable or disable the image smoothing on. + * @param {Boolean} overflowHidden If set to true it will enable image smoothing, false will disable it. + * @return {CanvasRenderingContext2D} Returns the source context. + */ public static setSmoothingEnabled(context: CanvasRenderingContext2D, value: boolean): CanvasRenderingContext2D { context['imageSmoothingEnabled'] = value; @@ -70,6 +133,14 @@ module Phaser { } + /** + * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast on webkit'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method setImageRenderingCrisp + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering crisp on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ public static setImageRenderingCrisp(canvas: HTMLCanvasElement): HTMLCanvasElement { canvas.style['image-rendering'] = 'crisp-edges'; @@ -80,6 +151,14 @@ module Phaser { } + /** + * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). + * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. + * + * @method setImageRenderingBicubic + * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. + * @return {HTMLCanvasElement} Returns the source canvas. + */ public static setImageRenderingBicubic(canvas: HTMLCanvasElement): HTMLCanvasElement { canvas.style['image-rendering'] = 'auto'; diff --git a/Phaser/utils/CircleUtils.ts b/Phaser/utils/CircleUtils.ts index 1b7e8bf3..433918ca 100644 --- a/Phaser/utils/CircleUtils.ts +++ b/Phaser/utils/CircleUtils.ts @@ -1,36 +1,40 @@ /// /** -* Phaser - CircleUtils -* -* A collection of methods useful for manipulating and comparing Circle objects. +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating and comparing Circle objects. + * + * @class CircleUtils + */ export 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: Phaser.Circle, out: Phaser.Circle = new Phaser.Circle): Phaser.Circle { + * Returns a new Circle object with the same values for the x, y, width, and height properties as the given Circle object. + * @method clone + * @param {Phaser.Circle} a The Circle object to be cloned. + * @param {Phaser.Circle} 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} The cloned Circle object. + */ + public static clone(a: Phaser.Circle, out: Phaser.Circle = new Phaser.Circle): Phaser.Circle { return out.setTo(a.x, a.y, a.diameter); } /** - * 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: Phaser.Circle, x: number, y: number): boolean { + * Return true if the given x/y coordinates are within the Circle object. + * @method contains + * @param {Phaser.Circle} a The Circle to be checked. + * @param {Number} x The X value of the coordinate to test. + * @param {Number} y The Y value of the coordinate to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + */ + public static contains(a: Phaser.Circle, x: number, y: number): boolean { // Check if x/y are within the bounds first if (x >= a.left && x <= a.right && y >= a.top && y <= a.bottom) @@ -45,38 +49,38 @@ module Phaser { } /** - * 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: Phaser.Circle, point: Phaser.Point): boolean { + * Return true if the coordinates of the given Point object are within this Circle object. + * @method containsPoint + * @param {Phaser.Circle} a The Circle object. + * @param {Phaser.Point} point The Point object to test. + * @return {Boolean} True if the coordinates are within this circle, otherwise false. + */ + public static containsPoint(a: Phaser.Circle, point: Phaser.Point): boolean { return CircleUtils.contains(a, point.x, point.y); } /** - * 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: Phaser.Circle, b: Phaser.Circle): boolean { + * Return true if the given Circle is contained entirely within this Circle object. + * @method containsCircle + * @param {Phaser.Circle} a The Circle object to test. + * @param {Phaser.Circle} b The Circle object to test. + * @return {Boolean} True if Circle B is contained entirely inside of Circle A, otherwise false. + */ + public static containsCircle(a: Phaser.Circle, b: Phaser.Circle): boolean { //return ((a.radius + b.radius) * (a.radius + b.radius)) >= Collision.distanceSquared(a.x, a.y, b.x, b.y); return true; } /** - * 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: Phaser.Circle, target: any, round: boolean = false): number { + * 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 {Phaser.Circle} a The Circle object. + * @param {Phaser.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. + */ + public static distanceBetween(a: Phaser.Circle, target: any, round: boolean = false): number { var dx = a.x - target.x; var dy = a.y - target.y; @@ -93,38 +97,38 @@ module Phaser { } /** - * 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: Phaser.Circle, b: Phaser.Circle): boolean { + * Determines whether the two Circle objects match. This method compares the x, y and diameter properties. + * @method equals + * @param {Phaser.Circle} a The first Circle object. + * @param {Phaser.Circle} b The second Circle object. + * @return {Boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. + */ + public static equals(a: Phaser.Circle, b: Phaser.Circle): boolean { return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); } /** - * Determines whether the two Circle objects intersect. - * This method checks the radius distances between the two Circle objects to see if they intersect. - * @method 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: Phaser.Circle, b: Phaser.Circle): boolean { + * 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 {Phaser.Circle} a The first Circle object. + * @param {Phaser.Circle} b The second Circle object. + * @return {Boolean} A value of true if the specified object intersects with this Circle object; otherwise false. + */ + public static intersects(a: Phaser.Circle, b: Phaser.Circle): boolean { return (Phaser.CircleUtils.distanceBetween(a, b) <= (a.radius + b.radius)); } /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method 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: Phaser.Circle, angle: number, asDegrees: boolean = false, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. + * @method circumferencePoint + * @param {Phaser.Circle} a The first Circle object. + * @param {Number} angle The angle in radians (unless asDegrees is true) to return the point from. + * @param {Boolean} asDegrees Is the given angle in radians (false) or degrees (true)? + * @param {Phaser.Point} [optional] output An optional Point object to put the result in to. If none specified a new Point object will be created. + * @return {Phaser.Point} The Point object holding the result. + */ + public static circumferencePoint(a: Phaser.Circle, angle: number, asDegrees: boolean = false, out: Phaser.Point = new Phaser.Point): Phaser.Point { if (asDegrees === true) { @@ -135,30 +139,14 @@ module Phaser { } - - /* - 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; - } - */ - - static intersectsRectangle(c: Phaser.Circle, r: Phaser.Rectangle): boolean { + /** + * Checks if the given Circle and Rectangle objects intersect. + * @method intersectsRectangle + * @param {Phaser.Circle} c The Circle object to test. + * @param {Phaser.Rectangle} r The Rectangle object to test. + * @return {Boolean} True if the two objects intersect, otherwise false. + */ + public static intersectsRectangle(c: Phaser.Circle, r: Phaser.Rectangle): boolean { var cx: number = Math.abs(c.x - r.x - r.halfWidth); var xDist: number = r.halfWidth + c.radius; diff --git a/Phaser/utils/ColorUtils.ts b/Phaser/utils/ColorUtils.ts index cb6c7d67..1325f9dc 100644 --- a/Phaser/utils/ColorUtils.ts +++ b/Phaser/utils/ColorUtils.ts @@ -1,52 +1,62 @@ /// /** -* Phaser - ColorUtils -* -* A collection of methods useful for manipulating color values. +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating and comparing colors. + * + * @class ColorUtils + */ export class ColorUtils { - static game: Phaser.Game; + /** + * A reference to the currently running Game. + * @property game + * @type {Phaser.Game} + */ + public static game: Phaser.Game; /** - * Given an alpha and 3 color values this will return an integer representation of it - * - * @param alpha {number} The Alpha value (between 0 and 255) - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xAARRGGBB) - */ - static getColor32(alpha: number, red: number, green: number, blue: number): number { + * Given an alpha and 3 color values this will return an integer representation of it + * + * @method getColor32 + * @param {Number} alpha The Alpha value (between 0 and 255) + * @param {Number} red The Red channel value (between 0 and 255) + * @param {Number} green The Green channel value (between 0 and 255) + * @param {Number} blue The Blue channel value (between 0 and 255) + * @return {Number} A native color value integer (format: 0xAARRGGBB) + */ + public static getColor32(alpha: number, red: number, green: number, blue: number): number { return alpha << 24 | red << 16 | green << 8 | blue; } /** - * Given 3 color values this will return an integer representation of it - * - * @param red {number} The Red channel value (between 0 and 255) - * @param green {number} The Green channel value (between 0 and 255) - * @param blue {number} The Blue channel value (between 0 and 255) - * - * @return A native color value integer (format: 0xRRGGBB) - */ - static getColor(red: number, green: number, blue: number): number { + * Given 3 color values this will return an integer representation of it. + * + * @method getColor + * @param {Number} red The Red channel value (between 0 and 255) + * @param {Number} green The Green channel value (between 0 and 255) + * @param {Number} blue The Blue channel value (between 0 and 255) + * @return {Number} A native color value integer (format: 0xRRGGBB) + */ + public static getColor(red: number, green: number, blue: number): number { return red << 16 | green << 8 | blue; } /** - * Get HSV color wheel values in an array which will be 360 elements in size - * - * @param alpha Alpha value for each color of the color wheel, between 0 (transparent) and 255 (opaque) - * - * @return Array - */ - public static getHSVColorWheel(alpha: number = 255) { + * Get HSV color wheel values in an array which will be 360 elements in size. + * + * @method getHSVColorWheel + * @param {Number} alpha Alpha value for each color of the color wheel, between 0 (transparent) and 255 (opaque) + * @return {Array} An array containing 360 elements corresponding to the HSV color wheel. + */ + public static getHSVColorWheel(alpha: number = 255):number[] { var colors = []; @@ -59,6 +69,13 @@ module Phaser { } + /** + * Converts the given hex string into an object containing the RGB values. + * + * @method hexToRGB + * @param {String} The string hex color to convert. + * @return {Object} An object with 3 properties: r,g and b. + */ public static hexToRGB(h: string) { var hex16 = (h.charAt(0) == "#") ? h.substring(1, 7) : h; @@ -75,14 +92,14 @@ module Phaser { } /** - * Returns a Complementary Color Harmony for the given color. - *

A complementary hue is one directly opposite the color given on the color wheel

- *

Value returned in 0xAARRGGBB format with Alpha set to 255.

- * - * @param color The color to base the harmony on - * - * @return 0xAARRGGBB format color value - */ + * Returns a Complementary Color Harmony for the given color. + *

A complementary hue is one directly opposite the color given on the color wheel

+ *

Value returned in 0xAARRGGBB format with Alpha set to 255.

+ * + * @method getComplementHarmony + * @param {Number} color The color to base the harmony on. + * @return {Number} 0xAARRGGBB format color value. + */ public static getComplementHarmony(color: number): number { var hsv: any = Phaser.ColorUtils.RGBtoHSV(color); @@ -94,15 +111,15 @@ module Phaser { } /** - * Returns an Analogous Color Harmony for the given color. - *

An Analogous harmony are hues adjacent to each other on the color wheel

- *

Values returned in 0xAARRGGBB format with Alpha set to 255.

- * - * @param color The color to base the harmony on - * @param threshold Control how adjacent the colors will be (default +- 30 degrees) - * - * @return Object containing 3 properties: color1 (the original color), color2 (the warmer analogous color) and color3 (the colder analogous color) - */ + * Returns an Analogous Color Harmony for the given color. + *

An Analogous harmony are hues adjacent to each other on the color wheel

+ *

Values returned in 0xAARRGGBB format with Alpha set to 255.

+ * + * @method getAnalogousHarmony + * @param {Number} color The color to base the harmony on. + * @param {Number} threshold Control how adjacent the colors will be (default +- 30 degrees) + * @return {Object} Object containing 3 properties: color1 (the original color), color2 (the warmer analogous color) and color3 (the colder analogous color) + */ public static getAnalogousHarmony(color: number, threshold: number = 30) { var hsv: any = Phaser.ColorUtils.RGBtoHSV(color); @@ -120,15 +137,15 @@ module Phaser { } /** - * Returns an Split Complement Color Harmony for the given color. - *

A Split Complement harmony are the two hues on either side of the color's Complement

- *

Values returned in 0xAARRGGBB format with Alpha set to 255.

- * - * @param color The color to base the harmony on - * @param threshold Control how adjacent the colors will be to the Complement (default +- 30 degrees) - * - * @return Object containing 3 properties: color1 (the original color), color2 (the warmer analogous color) and color3 (the colder analogous color) - */ + * Returns an Split Complement Color Harmony for the given color. + *

A Split Complement harmony are the two hues on either side of the color's Complement

+ *

Values returned in 0xAARRGGBB format with Alpha set to 255.

+ * + * @method getSplitComplementHarmony + * @param {Number} color The color to base the harmony on + * @param {Number} threshold Control how adjacent the colors will be to the Complement (default +- 30 degrees) + * @return {Object} An object containing 3 properties: color1 (the original color), color2 (the warmer analogous color) and color3 (the colder analogous color) + */ public static getSplitComplementHarmony(color: number, threshold: number = 30): any { var hsv: any = Phaser.ColorUtils.RGBtoHSV(color); @@ -147,14 +164,14 @@ module Phaser { } /** - * Returns a Triadic Color Harmony for the given color. - *

A Triadic harmony are 3 hues equidistant from each other on the color wheel

- *

Values returned in 0xAARRGGBB format with Alpha set to 255.

- * - * @param color The color to base the harmony on - * - * @return Object containing 3 properties: color1 (the original color), color2 and color3 (the equidistant colors) - */ + * Returns a Triadic Color Harmony for the given color. + *

A Triadic harmony are 3 hues equidistant from each other on the color wheel

+ *

Values returned in 0xAARRGGBB format with Alpha set to 255.

+ * + * @method getTriadicHarmony + * @param {Number} color The color to base the harmony on. + * @return {Object} An Object containing 3 properties: color1 (the original color), color2 and color3 (the equidistant colors) + */ public static getTriadicHarmony(color: number): any { var hsv: any = Phaser.ColorUtils.RGBtoHSV(color); @@ -167,13 +184,13 @@ module Phaser { } /** - * Returns a string containing handy information about the given color including string hex value, - * RGB format information and HSL information. Each section starts on a newline, 3 lines in total. - * - * @param color A color value in the format 0xAARRGGBB - * - * @return string containing the 3 lines of information - */ + * Returns a string containing handy information about the given color including string hex value, + * RGB format information and HSL information. Each section starts on a newline, 3 lines in total. + * + * @method getColorInfo + * @param {Number} color A color value in the format 0xAARRGGBB + * @return {String} string containing the 3 lines of information + */ public static getColorInfo(color: number): string { var argb: any = Phaser.ColorUtils.getRGB(color); @@ -193,12 +210,12 @@ module Phaser { } /** - * Return a string representation of the color in the format 0xAARRGGBB - * - * @param color The color to get the string representation for - * - * @return A string of length 10 characters in the format 0xAARRGGBB - */ + * Return a string representation of the color in the format 0xAARRGGBB + * + * @method RGBtoHexstring + * @param {Number} color The color to get the string representation for + * @return {String A string of length 10 characters in the format 0xAARRGGBB + */ public static RGBtoHexstring(color: number): string { var argb: any = Phaser.ColorUtils.getRGB(color); @@ -208,12 +225,12 @@ module Phaser { } /** - * Return a string representation of the color in the format #RRGGBB - * - * @param color The color to get the string representation for - * - * @return A string of length 10 characters in the format 0xAARRGGBB - */ + * Return a string representation of the color in the format #RRGGBB + * + * @method RGBtoWebstring + * @param {Number} color The color to get the string representation for + * @return {String} A string of length 10 characters in the format 0xAARRGGBB + */ public static RGBtoWebstring(color: number): string { var argb: any = Phaser.ColorUtils.getRGB(color); @@ -223,12 +240,12 @@ module Phaser { } /** - * Return a string containing a hex representation of the given color - * - * @param color The color channel to get the hex value for, must be a value between 0 and 255) - * - * @return A string of length 2 characters, i.e. 255 = FF, 0 = 00 - */ + * Return a string containing a hex representation of the given color + * + * @method colorToHexstring + * @param {Number} color The color channel to get the hex value for, must be a value between 0 and 255) + * @return {String} A string of length 2 characters, i.e. 255 = FF, 0 = 00 + */ public static colorToHexstring(color: number): string { var digits: string = "0123456789ABCDEF"; @@ -243,15 +260,15 @@ module Phaser { } /** - * Convert a HSV (hue, saturation, lightness) color space value to an RGB color - * - * @param h Hue degree, between 0 and 359 - * @param s Saturation, between 0.0 (grey) and 1.0 - * @param v Value, between 0.0 (black) and 1.0 - * @param alpha Alpha value to set per color (between 0 and 255) - * - * @return 32-bit ARGB color value (0xAARRGGBB) - */ + * Convert a HSV (hue, saturation, lightness) color space value to an RGB color + * + * @method HSVtoRGB + * @param {Number} h Hue degree, between 0 and 359 + * @param {Number} s Saturation, between 0.0 (grey) and 1.0 + * @param {Number} v Value, between 0.0 (black) and 1.0 + * @param {Number} alpha Alpha value to set per color (between 0 and 255) + * @return {Number} 32-bit ARGB color value (0xAARRGGBB) + */ static HSVtoRGB(h: number, s: number, v: number, alpha: number = 255): number { var result: number; @@ -304,12 +321,12 @@ module Phaser { } /** - * Convert an RGB color value to an object containing the HSV color space values: Hue, Saturation and Lightness - * - * @param color In format 0xRRGGBB - * - * @return Object with the properties hue (from 0 to 360), saturation (from 0 to 1.0) and lightness (from 0 to 1.0, also available under .value) - */ + * Convert an RGB color value to an object containing the HSV color space values: Hue, Saturation and Lightness + * + * @method RGBtoHSV + * @param {Number} color In format 0xRRGGBB + * @return {Object} An Object with the properties hue (from 0 to 360), saturation (from 0 to 1.0) and lightness (from 0 to 1.0, also available under .value) + */ public static RGBtoHSV(color: number): any { var rgb: any = Phaser.ColorUtils.getRGB(color); @@ -379,15 +396,14 @@ module Phaser { } /** - * + * Interpolates the two given colours based on the supplied step and currentStep properties. * @method interpolateColor * @param {Number} color1 * @param {Number} color2 * @param {Number} steps * @param {Number} currentStep * @param {Number} alpha - * @return {Number} - * @static + * @return {Number} The interpolated color value. */ public static interpolateColor(color1: number, color2: number, steps: number, currentStep: number, alpha: number = 255): number { @@ -403,31 +419,30 @@ module Phaser { } /** - * + * Interpolates the two given colours based on the supplied step and currentStep properties. * @method interpolateColorWithRGB * @param {Number} color - * @param {Number} r2 - * @param {Number} g2 - * @param {Number} b2 + * @param {Number} r + * @param {Number} g + * @param {Number} b * @param {Number} steps * @param {Number} currentStep - * @return {Number} - * @static + * @return {Number} The interpolated color value. */ - public static interpolateColorWithRGB(color: number, r2: number, g2: number, b2: number, steps: number, currentStep: number): number { + public static interpolateColorWithRGB(color: number, r: number, g: number, b: number, steps: number, currentStep: number): number { var src: any = Phaser.ColorUtils.getRGB(color); - var r: number = (((r2 - src.red) * currentStep) / steps) + src.red; - var g: number = (((g2 - src.green) * currentStep) / steps) + src.green; - var b: number = (((b2 - src.blue) * currentStep) / steps) + src.blue; + var or: number = (((r - src.red) * currentStep) / steps) + src.red; + var og: number = (((g - src.green) * currentStep) / steps) + src.green; + var ob: number = (((b - src.blue) * currentStep) / steps) + src.blue; - return Phaser.ColorUtils.getColor(r, g, b); + return Phaser.ColorUtils.getColor(or, og, ob); } /** - * + * Interpolates the two given colours based on the supplied step and currentStep properties. * @method interpolateRGB * @param {Number} r1 * @param {Number} g1 @@ -437,8 +452,7 @@ module Phaser { * @param {Number} b2 * @param {Number} steps * @param {Number} currentStep - * @return {Number} - * @static + * @return {Number} The interpolated color value. */ public static interpolateRGB(r1: number, g1: number, b1: number, r2: number, g2: number, b2: number, steps: number, currentStep: number): number { @@ -451,16 +465,16 @@ module Phaser { } /** - * Returns a random color value between black and white - *

Set the min value to start each channel from the given offset.

- *

Set the max value to restrict the maximum color used per channel

- * - * @param min The lowest value to use for the color - * @param max The highest value to use for the color - * @param alpha The alpha value of the returning color (default 255 = fully opaque) - * - * @return 32-bit color value with alpha - */ + * Returns a random color value between black and white + *

Set the min value to start each channel from the given offset.

+ *

Set the max value to restrict the maximum color used per channel

+ * + * @method getRandomColor + * @param {Number} min The lowest value to use for the color + * @param {Number} max The highest value to use for the color + * @param {Number} alpha The alpha value of the returning color (default 255 = fully opaque) + * @return {Number} 32-bit color value with alpha + */ public static getRandomColor(min: number = 0, max: number = 255, alpha: number = 255): number { // Sanity checks @@ -483,23 +497,23 @@ module Phaser { } /** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue - * - *

Alpha will only be set if it exist in the given color (0xAARRGGBB)

- * - * @param color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB) - * - * @return Object with properties: alpha, red, green, blue - */ + * Return the component parts of a color as an Object with the properties alpha, red, green, blue + * + *

Alpha will only be set if it exist in the given color (0xAARRGGBB)

+ * + * @method getRGB + * @param {Number} color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB) + * @return {Object} An Object with properties: alpha, red, green, blue + */ public static getRGB(color: number): any { return { alpha: color >>> 24, red: color >> 16 & 0xFF, green: color >> 8 & 0xFF, blue: color & 0xFF }; } /** - * + * Returns a CSS friendly string value from the given color. * @method getWebRGB * @param {Number} color - * @return {Any} + * @return {String} A string in the format: 'rgba(r,g,b,a)' */ public static getWebRGB(color: number): any { @@ -513,56 +527,56 @@ module Phaser { } /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255 - * - * @param color In the format 0xAARRGGBB - * - * @return The Alpha component of the color, will be between 0 and 255 (0 being no Alpha, 255 full Alpha) - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255 + * + * @method getAlpha + * @param {Number} color In the format 0xAARRGGBB + * @return {Number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)) + */ public static getAlpha(color: number): number { return color >>> 24; } /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1 - * - * @param color In the format 0xAARRGGBB - * - * @return The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)) - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1 + * + * @method getAlphaFloat + * @param {Number} color In the format 0xAARRGGBB + * @return {Number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)) + */ public static getAlphaFloat(color: number): number { return (color >>> 24) / 255; } /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255 - * - * @param color In the format 0xAARRGGBB - * - * @return The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red) - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255 + * + * @method getRed + * @param {Number} color In the format 0xAARRGGBB + * @return {Number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red) + */ public static getRed(color: number): number { return color >> 16 & 0xFF; } /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255 - * - * @param color In the format 0xAARRGGBB - * - * @return The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green) - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255 + * + * @method getGreen + * @param {Number} color In the format 0xAARRGGBB + * @return {Number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green) + */ public static getGreen(color: number): number { return color >> 8 & 0xFF; } /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255 - * - * @param color In the format 0xAARRGGBB - * - * @return The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue) - */ + * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255 + * + * @method getBlue + * @param {Number} color In the format 0xAARRGGBB + * @return {Number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue) + */ public static getBlue(color: number): number { return color & 0xFF; } diff --git a/Phaser/utils/DebugUtils.ts b/Phaser/utils/DebugUtils.ts index 885eb969..7dbb7b98 100644 --- a/Phaser/utils/DebugUtils.ts +++ b/Phaser/utils/DebugUtils.ts @@ -1,32 +1,85 @@ /// /** -* Phaser - DebugUtils -* -* A collection of methods for displaying debug information about game objects. +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods for displaying debug information about game objects. + * + * @class DebugUtils + */ export class DebugUtils { - static game: Phaser.Game; + /** + * A reference to the currently running Game. + * @property game + * @type {Phaser.Game} + */ + public static game: Phaser.Game; /** - * The context to which the render debug info will be drawn. - * Defaults to the Game.Stage.context, but can be redirected anywhere. - * @type {CanvasRenderingContext2D} - */ - static context: CanvasRenderingContext2D; + * The context to which the debug info will be drawn. + * Defaults to the Game.Stage.context, but can be redirected anywhere. + * @property context + * @type {CanvasRenderingContext2D} + */ + public static context: CanvasRenderingContext2D; - static currentX: number; - static currentY: number; - static font: string = '14px Courier'; - static lineHeight: number = 16; - static currentColor: string; - static renderShadow: boolean = true; + /** + * An internally used value that holds the X value of the debug text to be rendered. + * @property currentX + * @type {Number} + */ + public static currentX: number; - static start(x: number, y: number, color: string = 'rgb(255,255,255)') { + /** + * An internally used value that holds the Y value of the debug text to be rendered. + * @property currentY + * @type {Number} + */ + public static currentY: number; + + /** + * The font of the debug text to be rendered. + * @property font + * @type {String} + */ + public static font: string = '14px Courier'; + + /** + * The height in pixels of a line of debug text. If you adjust the font size then adjust this accordingly. + * @property lineHeight + * @type {Number} + */ + public static lineHeight: number = 16; + + /** + * The color of the debug text to be rendered in CSS string format (i.e. 'rgb(r,g,b)') + * @property font + * @type {String} + */ + public static currentColor: string; + + /** + * If set to true this will render a shadow below any debug text, often making it easier to read. + * @property renderShadow + * @type {Boolean} + */ + public static renderShadow: boolean = true; + + /** + * Internal method that resets the debug output values. + * @method start + * @param {Number} x The X value the debug info will start from. + * @param {Number} y The Y value the debug info will start from. + * @param {String} color The color the debug info will drawn in. + */ + public static start(x: number, y: number, color: string = 'rgb(255,255,255)') { Phaser.DebugUtils.currentX = x; Phaser.DebugUtils.currentY = y; @@ -37,7 +90,14 @@ module Phaser { } - static line(text: string, x:number = null, y:number = null) { + /** + * Internal method that outputs a single line of text. + * @method line + * @param {String} text The line of text to draw. + * @param {Number} x The X value the debug info will start from. + * @param {Number} y The Y value the debug info will start from. + */ + public static line(text: string, x:number = null, y:number = null) { if (x !== null) { @@ -62,7 +122,7 @@ module Phaser { } - static renderSpriteCorners(sprite: Phaser.Sprite, color: string = 'rgb(255,0,255)') { + public static renderSpriteCorners(sprite: Phaser.Sprite, color: string = 'rgb(255,0,255)') { Phaser.DebugUtils.start(0, 0, color); @@ -79,7 +139,7 @@ module Phaser { * @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) */ - static renderSoundInfo(sound: Phaser.Sound, x: number, y: number, color: string = 'rgb(255,255,255)') { + public static renderSoundInfo(sound: Phaser.Sound, x: number, y: number, color: string = 'rgb(255,255,255)') { Phaser.DebugUtils.start(x, y, color); diff --git a/Phaser/utils/PointUtils.ts b/Phaser/utils/PointUtils.ts index 0bb43bfa..2f7416a0 100644 --- a/Phaser/utils/PointUtils.ts +++ b/Phaser/utils/PointUtils.ts @@ -1,74 +1,77 @@ /// /** -* Phaser - PointUtils -* -* A collection of methods useful for manipulating and comparing Point objects. -* -* TODO: interpolate & polar +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating and comparing Point objects. + * + * @class PointUtils + */ export class PointUtils { /** - * Adds the coordinates of two points together to create a new point. - * @method add - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - static add(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * Adds the coordinates of two points together to create a new point. + * @method add + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ + public static add(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.x + b.x, a.y + b.y); } /** - * Subtracts the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - static subtract(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * Subtracts the coordinates of two points to create a new point. + * @method subtract + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ + public static subtract(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.x - b.x, a.y - b.y); } /** - * Multiplies the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - static multiply(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * Multiplies the coordinates of two points to create a new point. + * @method subtract + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ + public static multiply(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.x * b.x, a.y * b.y); } /** - * Divides the coordinates of two points to create a new point. - * @method subtract - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - static divide(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * Divides the coordinates of two points to create a new point. + * @method subtract + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ + public static divide(a: Phaser.Point, b: Phaser.Point, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.x / b.x, a.y / b.y); } /** - * Clamps the Point object values to be between the given min and max - * @method clamp - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - static clamp(a: Phaser.Point, min: number, max: number): Phaser.Point { + * Clamps the Point object values to be between the given min and max + * @method clamp + * @param {Phaser.Point} a The point. + * @param {Number} min The minimum value to clamp this Point to + * @param {Number} max The maximum value to clamp this Point to + * @return {Phaser.Point} This Point object. + */ + public static clamp(a: Phaser.Point, min: number, max: number): Phaser.Point { Phaser.PointUtils.clampX(a, min, max); Phaser.PointUtils.clampY(a, min, max); @@ -77,14 +80,14 @@ module Phaser { } /** - * Clamps the x value of the given Point object to be between the min and max values. - * @method clampX - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - static clampX(a: Phaser.Point, min: number, max: number): Phaser.Point { + * Clamps the x value of the given Point object to be between the min and max values. + * @method clampX + * @param {Phaser.Point} a The point. + * @param {Number} min The minimum value to clamp this Point to + * @param {Number} max The maximum value to clamp this Point to + * @return {Phaser.Point} This Point object. + */ + public static clampX(a: Phaser.Point, min: number, max: number): Phaser.Point { a.x = Math.max(Math.min(a.x, max), min); return a; @@ -92,14 +95,14 @@ module Phaser { } /** - * Clamps the y value of the given Point object to be between the min and max values. - * @method clampY - * @param {Point} a - The point. - * @param {number} The minimum value to clamp this Point to - * @param {number} The maximum value to clamp this Point to - * @return {Point} This Point object. - **/ - static clampY(a: Phaser.Point, min: number, max: number): Phaser.Point { + * Clamps the y value of the given Point object to be between the min and max values. + * @method clampY + * @param {Phaser.Point} a The point. + * @param {Number} min The minimum value to clamp this Point to + * @param {Number} max The maximum value to clamp this Point to + * @return {Phaser.Point} This Point object. + */ + public static clampY(a: Phaser.Point, min: number, max: number): Phaser.Point { a.y = Math.max(Math.min(a.y, max), min); return a; @@ -107,24 +110,24 @@ module Phaser { } /** - * Creates a copy of the given Point. - * @method clone - * @param {Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Point} The new Point object. - **/ - static clone(a: Phaser.Point, output: Phaser.Point = new Phaser.Point): Phaser.Point { + * Creates a copy of the given Point. + * @method clone + * @param {Phaser.Point} output Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The new Point object. + */ + public static clone(a: Phaser.Point, output: Phaser.Point = new Phaser.Point): Phaser.Point { return output.setTo(a.x, a.y); } /** - * Returns the distance between the two given Point objects. - * @method distanceBetween - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @param {Boolean} round - Round the distance to the nearest integer (default false) - * @return {Number} The distance between the two Point objects. - **/ - static distanceBetween(a: Phaser.Point, b: Phaser.Point, round: boolean = false): number { + * Returns the distance between the two given Point objects. + * @method distanceBetween + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @param {Boolean} round Round the distance to the nearest integer (default false) + * @return {Number} The distance between the two Point objects. + */ + public static distanceBetween(a: Phaser.Point, b: Phaser.Point, round: boolean = false): number { var dx = a.x - b.x; var dy = a.y - b.y; @@ -141,49 +144,52 @@ module Phaser { } /** - * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. - * @method equals - * @param {Point} a - The first Point object. - * @param {Point} b - The second Point object. - * @return {Boolean} A value of true if the Points are equal, otherwise false. - **/ - static equals(a: Phaser.Point, b: Phaser.Point): boolean { + * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. + * @method equals + * @param {Phaser.Point} a The first Point object. + * @param {Phaser.Point} b The second Point object. + * @return {Boolean} A value of true if the Points are equal, otherwise false. + */ + public static equals(a: Phaser.Point, b: Phaser.Point): boolean { return (a.x == b.x && a.y == b.y); } /** - * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. - * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). - * @method interpolate - * @param {Point} pointA - The first Point object. - * @param {Point} pointB - The second Point object. - * @param {Number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. - * @return {Point} The new interpolated Point object. - **/ - //static interpolate(pointA, pointB, f) { + * Determines a point between two specified points. The parameter f determines where the new interpolated point is located relative to the two end points specified by parameters pt1 and pt2. + * The closer the value of the parameter f is to 1.0, the closer the interpolated point is to the first point (parameter pt1). The closer the value of the parameter f is to 0, the closer the interpolated point is to the second point (parameter pt2). + * @method interpolate + * @param {Phaser.Point} pointA The first Point object. + * @param {Phaser.Point} pointB The second Point object. + * @param {Number} f The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned. + * @return {Phaser.Point} The new interpolated Point object. + */ + //public static interpolate(pointA, pointB, f) { + // TODO! //} /** - * Converts a pair of polar coordinates to a Cartesian point coordinate. - * @method polar - * @param {Number} length - The length coordinate of the polar pair. - * @param {Number} angle - The angle, in radians, of the polar pair. - * @return {Point} The new Cartesian Point object. - **/ - //static polar(length, angle) { + * Converts a pair of polar coordinates to a Cartesian point coordinate. + * @method polar + * @param {Number} length The length coordinate of the polar pair. + * @param {Number} angle The angle, in radians, of the polar pair. + * @return {Phaser.Point} The new Cartesian Point object. + */ + //public static polar(length, angle) { + // TODO! //} /** * Rotates a Point around the x/y coordinates given to the desired angle. - * @param a {Point} The Point object to rotate. - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point + * @method rotate + * @param {Phaser.Point} a The Point object to rotate. + * @param {Number} x The x coordinate of the anchor point + * @param {Number} y The y coordinate of the anchor point * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. * @param {Boolean} asDegrees Is the given rotation in radians (false) or degrees (true)? * @param {Number} distance An optional distance constraint between the Point and the anchor. - * @return The modified point object + * @return {Phaser.Point} The modified point object */ - static rotate(a: Phaser.Point, x: number, y: number, angle: number, asDegrees: boolean = false, distance: number = null): Phaser.Point { + public static rotate(a: Phaser.Point, x: number, y: number, angle: number, asDegrees: boolean = false, distance: number = null): Phaser.Point { if (asDegrees) { @@ -202,16 +208,15 @@ module Phaser { /** * Rotates a Point around the given Point to the desired angle. - * @param a {Point} The Point object to rotate. - * @param b {Point} The Point object to serve as point of rotation. - * @param x {number} The x coordinate of the anchor point - * @param y {number} The y coordinate of the anchor point - * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. + * @method rotateAroundPoint + * @param {Phaser.Point} a The Point object to rotate. + * @param {Phaser.Point} b The Point object to serve as point of rotation. + * @param {Number} angle The angle in radians (unless asDegrees is true) to rotate the Point to. * @param {Boolean} asDegrees Is the given rotation in radians (false) or degrees (true)? * @param {Number} distance An optional distance constraint between the Point and the anchor. - * @return The modified point object + * @return {Phaser.Point} The modified point object */ - static rotateAroundPoint(a: Phaser.Point, b: Phaser.Point, angle: number, asDegrees: boolean = false, distance: number = null): Phaser.Point { + public static rotateAroundPoint(a: Phaser.Point, b: Phaser.Point, angle: number, asDegrees: boolean = false, distance: number = null): Phaser.Point { return Phaser.PointUtils.rotate(a, b.x, b.y, angle, asDegrees, distance); } diff --git a/Phaser/utils/RectangleUtils.ts b/Phaser/utils/RectangleUtils.ts index 09f3859f..3d058993 100644 --- a/Phaser/utils/RectangleUtils.ts +++ b/Phaser/utils/RectangleUtils.ts @@ -1,48 +1,51 @@ /// /** -* Phaser - RectangleUtils -* -* A collection of methods useful for manipulating and comparing Rectangle objects. -* -* TODO: Check docs + overlap + intersect + toPolygon? +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating and comparing Rectangle objects. + * + * @class RectangleUtils + */ export class RectangleUtils { /** * Get the location of the Rectangles top-left corner as a Point object. * @method getTopLeftAsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. - **/ - static getTopLeftAsPoint(a: Phaser.Rectangle, out: Phaser.Point = new Phaser.Point): Phaser.Point { + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. + */ + public static getTopLeftAsPoint(a: Phaser.Rectangle, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.x, a.y); } /** * Get the location of the Rectangles bottom-right corner as a Point object. * @method getTopLeftAsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} out - Optional Point to store the value in, if not supplied a new Point object will be created. - * @return {Point} The new Point object. + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Point} out Optional Point to store the value in, if not supplied a new Point object will be created. + * @return {Phaser.Point} The new Point object. **/ - static getBottomRightAsPoint(a: Phaser.Rectangle, out: Phaser.Point = new Phaser.Point): Phaser.Point { + public static getBottomRightAsPoint(a: Phaser.Rectangle, out: Phaser.Point = new Phaser.Point): Phaser.Point { return out.setTo(a.right, a.bottom); } /** * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. * @method inflate - * @param {Rectangle} a - The Rectangle object. + * @param {Phaser.Rectangle} a The Rectangle object. * @param {Number} dx The amount to be added to the left side of the Rectangle. * @param {Number} dy The amount to be added to the bottom side of the Rectangle. - * @return {Rectangle} This Rectangle object. - **/ - static inflate(a: Phaser.Rectangle, dx: number, dy: number): Phaser.Rectangle { + * @return {Phaser.Rectangle} This Rectangle object. + */ + public static inflate(a: Phaser.Rectangle, dx: number, dy: number): Phaser.Rectangle { a.x -= dx; a.width += 2 * dx; @@ -57,56 +60,56 @@ module Phaser { /** * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. * @method inflatePoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. - * @return {Rectangle} The Rectangle object. - **/ - static inflatePoint(a: Phaser.Rectangle, point: Phaser.Point): Phaser.Rectangle { + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Point} point The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. + * @return {Phaser.Rectangle} The Rectangle object. + */ + public static inflatePoint(a: Phaser.Rectangle, point: Phaser.Point): Phaser.Rectangle { return Phaser.RectangleUtils.inflate(a, point.x, point.y); } /** * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. * @method size - * @param {Rectangle} a - The Rectangle object. - * @param {Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Point} The size of the Rectangle object - **/ - static size(a: Phaser.Rectangle, output: Phaser.Point = new Phaser.Point): Phaser.Point { + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Point} output Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. + * @return {Phaser.Point} The size of the Rectangle object + */ + public static size(a: Phaser.Rectangle, output: Phaser.Point = new Phaser.Point): Phaser.Point { return output.setTo(a.width, a.height); } /** * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. * @method clone - * @param {Rectangle} a - The Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} - **/ - static clone(a: Phaser.Rectangle, output: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Rectangle} output Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} + */ + public static clone(a: Phaser.Rectangle, output: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { return output.setTo(a.x, a.y, a.width, a.height); } /** * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. * @method contains - * @param {Rectangle} a - The Rectangle object. + * @param {Phaser.Rectangle} a The Rectangle object. * @param {Number} x The x coordinate of the point to test. * @param {Number} y The y coordinate of the point to test. * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - static contains(a: Phaser.Rectangle, x: number, y: number): boolean { + */ + public static contains(a: Phaser.Rectangle, x: number, y: number): boolean { return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom); } /** * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. * @method containsPoint - * @param {Rectangle} a - The Rectangle object. - * @param {Point} point The point object being checked. Can be Point or any object with .x and .y values. + * @param {Phaser.Rectangle} a The Rectangle object. + * @param {Phaser.Point} point The point object being checked. Can be Point or any object with .x and .y values. * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - static containsPoint(a: Phaser.Rectangle, point: Phaser.Point): boolean { + */ + public static containsPoint(a: Phaser.Rectangle, point: Phaser.Point): boolean { return Phaser.RectangleUtils.contains(a, point.x, point.y); } @@ -114,11 +117,11 @@ module Phaser { * Determines whether the first Rectangle object is fully contained within the second Rectangle object. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. * @method containsRect - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} a The first Rectangle object. + * @param {Phaser.Rectangle} b The second Rectangle object. * @return {Boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - **/ - static containsRect(a: Phaser.Rectangle, b: Phaser.Rectangle): boolean { + */ + public static containsRect(a: Phaser.Rectangle, b: Phaser.Rectangle): boolean { // If the given rect has a larger volume than this one then it can never contain it if (a.volume > b.volume) @@ -134,23 +137,23 @@ module Phaser { * Determines whether the two Rectangles are equal. * This method compares the x, y, width and height properties of each Rectangle. * @method equals - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} a The first Rectangle object. + * @param {Phaser.Rectangle} b The second Rectangle object. * @return {Boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. - **/ - static equals(a: Phaser.Rectangle, b: Phaser.Rectangle): boolean { + */ + public static equals(a: Phaser.Rectangle, b: Phaser.Rectangle): boolean { return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height); } /** * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. * @method intersection - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. - **/ - static intersection(a: Phaser.Rectangle, b: Phaser.Rectangle, out: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { + * @param {Phaser.Rectangle} a The first Rectangle object. + * @param {Phaser.Rectangle} b The second Rectangle object. + * @param {Phaser.Rectangle} output Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. + */ + public static intersection(a: Phaser.Rectangle, b: Phaser.Rectangle, out: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { if (Phaser.RectangleUtils.intersects(a, b)) { @@ -168,12 +171,12 @@ module Phaser { * Determines whether the two Rectangles intersect with each other. * This method checks the x, y, width, and height properties of the Rectangles. * @method intersects - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. + * @param {Phaser.Rectangle} a The first Rectangle object. + * @param {Phaser.Rectangle} b The second Rectangle object. * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 * @return {Boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - **/ - static intersects(a: Phaser.Rectangle, b: Phaser.Rectangle, tolerance: number = 0): boolean { + */ + public static intersects(a: Phaser.Rectangle, b: Phaser.Rectangle, tolerance: number = 0): boolean { return !(a.left > b.right + tolerance || a.right < b.left - tolerance || a.top > b.bottom + tolerance || a.bottom < b.top - tolerance); } @@ -186,20 +189,20 @@ module Phaser { * @param {Number} bottomt * @param {Number} tolerance A tolerance value to allow for an intersection test with padding, default to 0 * @return {Boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. - **/ - static intersectsRaw(a: Phaser.Rectangle, left: number, right: number, top: number, bottom: number, tolerance: number = 0): boolean { + */ + public static intersectsRaw(a: Phaser.Rectangle, left: number, right: number, top: number, bottom: number, tolerance: number = 0): boolean { return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); } /** * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. * @method union - * @param {Rectangle} a - The first Rectangle object. - * @param {Rectangle} b - The second Rectangle object. - * @param {Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Rectangle} A Rectangle object that is the union of the two Rectangles. - **/ - static union(a: Phaser.Rectangle, b: Phaser.Rectangle, out: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { + * @param {Phaser.Rectangle} a The first Rectangle object. + * @param {Phaser.Rectangle} b The second Rectangle object. + * @param {Phaser.Rectangle} output Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. + * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. + */ + public static union(a: Phaser.Rectangle, b: Phaser.Rectangle, out: Phaser.Rectangle = new Phaser.Rectangle): Phaser.Rectangle { return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right), Math.max(a.bottom, b.bottom)); } diff --git a/Phaser/utils/SpriteUtils.ts b/Phaser/utils/SpriteUtils.ts index 572af9fa..b6ec0855 100644 --- a/Phaser/utils/SpriteUtils.ts +++ b/Phaser/utils/SpriteUtils.ts @@ -1,26 +1,49 @@ /// /** -* Phaser - SpriteUtils -* -* A collection of methods useful for manipulating and checking Sprites. +* @author Richard Davey +* @copyright 2013 Photon Storm Ltd. +* @license https://github.com/photonstorm/phaser/blob/master/license.txt MIT License +* @module Phaser */ - module Phaser { + /** + * A collection of methods useful for manipulating and comparing Sprites. + * + * @class SpriteUtils + */ export class SpriteUtils { - static _tempPoint: Phaser.Point; - static _sin: number; - static _cos: number; + /** + * A temporary internal variable. + * @property _tempPoint + * @type {Phaser.Point} + */ + public static _tempPoint: Phaser.Point; /** - * Updates a Sprites cameraView Rectangle based on the given camera, sprite world position and rotation - * @param camera {Camera} The Camera to use in the view - * @param sprite {Sprite} The Sprite that will have its cameraView property modified - * @return {Rectangle} A reference to the Sprite.cameraView property - */ - static updateCameraView(camera: Phaser.Camera, sprite: Phaser.Sprite): Phaser.Rectangle { + * A temporary internal variable. + * @property _sin + * @type {Number} + */ + public static _sin: number; + + /** + * A temporary internal variable. + * @property _cos + * @type {Number} + */ + public static _cos: number; + + /** + * Updates a Sprites cameraView Rectangle based on the given camera, sprite world position and rotation. + * @method updateCameraView + * @param {Camera} camera The Camera to use in the view + * @param {Sprite} sprite The Sprite that will have its cameraView property modified + * @return {Rectangle} A reference to the Sprite.cameraView property + */ + public static updateCameraView(camera: Phaser.Camera, sprite: Phaser.Sprite): Phaser.Rectangle { if (sprite.rotation == 0 || sprite.texture.renderRotation == false) { @@ -66,7 +89,13 @@ module Phaser { } - static getAsPoints(sprite: Phaser.Sprite): Phaser.Point[] { + /** + * Returns an array containing 4 Point objects corresponding to the 4 corners of the sprite bounds. + * @method getAsPoints + * @param {Sprite} sprite The Sprite that will have its cameraView property modified + * @return {Array} An array of Point objects. + */ + public static getAsPoints(sprite: Phaser.Sprite): Phaser.Point[] { var out: Phaser.Point[] = []; @@ -138,18 +167,17 @@ module Phaser { } */ - /** * Checks to see if the given x and y coordinates overlaps this Sprite, taking scaling and rotation into account. * The coordinates must be given in world space, not local or camera space. * - * @param sprite {Sprite} The Sprite to check. It will take scaling and rotation into account. - * @param x {Number} The x coordinate in world space. - * @param y {Number} The y coordinate in world space. - * - * @return Whether or not the point overlaps this object. + * @method overlapsXY + * @param {Sprite} sprite The Sprite to check. It will take scaling and rotation into account. + * @param {Number} x The x coordinate in world space. + * @param {Number} y The y coordinate in world space. + * @return {Boolean} Whether or not the point overlaps this object. */ - static overlapsXY(sprite: Phaser.Sprite, x: number, y: number): boolean { + public static overlapsXY(sprite: Phaser.Sprite, x: number, y: number): boolean { // if rotation == 0 then just do a rect check instead! if (sprite.transform.rotation == 0) @@ -185,23 +213,24 @@ module Phaser { * Checks to see if the given point overlaps this Sprite, taking scaling and rotation into account. * The point must be given in world space, not local or camera space. * - * @param sprite {Sprite} The Sprite to check. It will take scaling and rotation into account. - * @param point {Point} The point in world space you want to check. - * - * @return Whether or not the point overlaps this object. + * @method overlapsPoint + * @param {Sprite} sprite The Sprite to check. It will take scaling and rotation into account. + * @param {Point} point The point in world space you want to check. + * @return {Boolean} Whether or not the point overlaps this object. */ - static overlapsPoint(sprite: Phaser.Sprite, point: Phaser.Point): boolean { + public static overlapsPoint(sprite: Phaser.Sprite, point: Phaser.Point): boolean { return Phaser.SpriteUtils.overlapsXY(sprite, point.x, point.y); } /** * 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. + * @method onScreen + * @param {Sprite} sprite The Sprite to check. It will take scaling and rotation into account. + * @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: Phaser.Sprite, camera: Phaser.Camera = null): boolean { + public static onScreen(sprite: Phaser.Sprite, camera: Phaser.Camera = null): boolean { if (camera == null) { @@ -217,12 +246,13 @@ module Phaser { /** * Call this to figure out the on-screen position of the object. * - * @param point {Point} Takes a Point 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. - * + * @method getScreenXY + * @param {Sprite} sprite The Sprite to check. + * @param {Point} point Takes a Point 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: Phaser.Sprite, point: Phaser.Point = null, camera: Phaser.Camera = null): Phaser.Point { + public static getScreenXY(sprite: Phaser.Sprite, point: Phaser.Point = null, camera: Phaser.Camera = null): Phaser.Point { if (point == null) { @@ -258,17 +288,17 @@ module Phaser { */ /** - * Handy for reviving game objects. - * Resets their existence flags and position. + * 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. + * @method reset + * @param {Sprite} sprite The Sprite to reset. + * @param {number} x The new X position of this object. + * @param {number} y The new Y position of this object. + * @return {Sprite} The reset Sprite object. */ - static reset(sprite: Phaser.Sprite, x: number, y: number) { + public static reset(sprite: Phaser.Sprite, x: number, y: number):Phaser.Sprite { sprite.revive(); - //sprite.body.touching = Types.NONE; - //sprite.body.wasTouching = Types.NONE; sprite.x = x; sprite.y = y; sprite.body.velocity.x = 0; @@ -276,6 +306,8 @@ module Phaser { sprite.body.position.x = x; sprite.body.position.y = y; + return sprite; + } /** @@ -283,37 +315,18 @@ module Phaser { * in the world. But by setting the bounds (which are given in world dimensions, not screen dimensions) * it can be stopped from leaving the world, or a section of it. * - * @param x {number} x position of the bound - * @param y {number} y position of the bound - * @param width {number} width of its bound - * @param height {number} height of its bound + * @method setBounds + * @param {number} x x position of the bound + * @param {number} y y position of the bound + * @param {number} width width of its bound + * @param {number} height height of its bound */ - static setBounds(x: number, y: number, width: number, height: number) { + public static setBounds(x: number, y: number, width: number, height: number) { - //this.worldBounds = new Quad(x, y, width, height); + // Needed? } - /** - * This function creates a flat colored square image dynamically. - * @param width {number} The width of the sprite you want to generate. - * @param height {number} The height of the sprite you want to generate. - * @param [color] {number} specifies the color of the generated block. (format is 0xAARRGGBB) - * @return {Sprite} Sprite instance itself. - */ - /* - static makeGraphic(width: number, height: number, color: string = 'rgb(255,255,255)'): Sprite { - - this._texture = null; - this.width = width; - this.height = height; - this.fillColor = color; - this._dynamicTexture = false; - - return this; - } - */ - } } \ No newline at end of file diff --git a/Plugins/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache b/Plugins/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache new file mode 100644 index 0000000000000000000000000000000000000000..594d24c2ae1a9f2edacb2a57298a8a5a6b29fe2b GIT binary patch literal 6226 zcmeHLZBrXJ5VpZ67($C_N)l)ir%l_uI5&2I@G`@PVB?l)VHn#(JHs(VzLRYQ-N_^A zFfPMy=`ZN?C$_tOIS3HfAM6=ESRSv>EA5L`E8U}wL?e;NztHd(+x;;h?k;zf)Usl% z1Fi!qiY9Qmw6fCkq`#BfP9+bR(p>tRnT(ajPb!%Wgb5Ve^jTmO6{+NYP!`vg8A0#!SHJuvzq2tTGm z$Od!YYt6i}Xl|bw=A&1721aM4U*Xj}7i`|4zRO)|Sa&3H^3je%*UeTU~qT zLw>u8CpY+4rIG^Xsm(Pvb6hdUNX40+t-FS*BBRQw?Nd|Jv(;;i>AI2?h!Dr2Zly|#Xo>gC5Bb#)kVI2vqN@3^{Xbd;jQ$f9sJ4MX`I`#pizPjBZo!_I;a=t z5rW(JIFPA$3?CpA4N$B7Y9} zvDS#M@X6C$kO%NI1-!JilwQiL$G?XE2@D*5$vhIP!F|sq2*hKSD+GDedSYiRfw9H- zk;g#Z_LyrH0H31yKkO~30AX7nHCX_WH~om@smoAc5d>0w2?(ldDDh3dUhQ(FWXr23 zAd>FKND=NDg8Q&CVCZSThKe=n$_9!&>vuLFa?+ZA5+r`;;aZ7#fUQky>~k1rWd;5Vyf>FoYJ_(vLq`N=F7Uj--_CEPjXjV`1pa0=Yi8(^Hgch>LkXKcgj#YpZR~~>SJ=Nos~jAG zzgfvFS68dAtJ$oxn&HcQf=sS`#M0YPxDMId_BF_$@w?=W21v8W<+k4lwR(uckGbmx zO>o{Q1zyE%ZJlWF$tyL3qjP~@6}5tJVczDxBOI=wH97D0~D~O@JgF*eRvEH;jGEFO3ie6e$7|y)mPc| z^{;Mn?dsSwAh718zn@?O)kNT5Ugds z+bT!EFnzpYuBLmavWps_r;|4dh(QT*#mrQGA&+#zq-w@4nH=58#Tow4t* zckc8T;cKcN6(m;aaO<40?~%W7TE4j^)H-9&uzwH;>N)C}IW6)gos3j7I%6-8wRG#b zToJyNB9ufJkiA4QjHO^{RJ=cgH7;-)0g|#(gu|%aYcDLVI<@h?M{lYBt3Qw4Qc(r* GVER9KYv`>2 literal 0 HcmV?d00001 diff --git a/SpecialFX/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs b/SpecialFX/obj/Debug/TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs new file mode 100644 index 00000000..e69de29b diff --git a/SpecialFX/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs b/SpecialFX/obj/Debug/TemporaryGeneratedFile_5937a670-0e60-4077-877b-f7221da3dda1.cs new file mode 100644 index 00000000..e69de29b diff --git a/SpecialFX/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs b/SpecialFX/obj/Debug/TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs new file mode 100644 index 00000000..e69de29b