32 Commits
Author SHA1 Message Date
Richard Davey b5b5a99dce Preparing for 0.9.6 work 2013-05-02 20:54:28 +01:00
Richard Davey be982b4322 Updated readme and new minified build 2013-05-02 14:03:41 +01:00
Richard Davey 493380a51e Updated readme for official release. 2013-05-02 05:20:01 +01:00
Richard Davey 0a08e1ae0e Removed un-needed file and added SoundManager fix. 2013-05-02 05:16:16 +01:00
Richard Davey e39073d07b Updated readme 2013-05-02 05:02:05 +01:00
Richard Davey 54a5e6477c Lots of new tile map commands and tests. 2013-05-02 05:01:34 +01:00
Richard Davey 2a5b6ef12a Large Tilemap collision overhaul. Proper callback support, optimised collision checks and lots more. 2013-05-02 03:37:45 +01:00
Richard Davey e62b300a25 Added Camera Mirror FX and test case. 2013-05-02 01:02:06 +01:00
Richard Davey 7d98a1bb9d New FXManager system and Camera FX now in place. 2013-05-01 04:10:21 +01:00
Richard Davey c5cccf3283 Large refactoring of the pause and boot screens in Stage and various other small fixes 2013-04-29 02:41:19 +01:00
Richard Davey 9f23c378a1 0.9.4 release 2013-04-28 22:10:12 +01:00
Richard Davey b6f8a3fba6 Final 0.9.4 release 2013-04-28 22:10:11 +01:00
Richard Davey cb9cb6e894 Github Bug Fixes 2013-04-28 22:04:37 +01:00
Richard Davey e948f1e3be Fixed daft issue in Camera and fully implemented tilemap collision. 2013-04-28 22:04:36 +01:00
Richard Davey 4c21ac0d87 Tilemap collision is now working but all Camera following seems to be broken as a result. Awesome. 2013-04-28 22:04:36 +01:00
Richard Davey db9b8ec370 Merge pull request #11 from HackManiac/amd
Automatic creation of UMD wrapped variant of Phaser
2013-04-28 13:37:09 -07:00
HackManiacandDaniel Wippermann f66e0e9254 Automatic creation of UMD wrapped variant of Phaser 2013-04-26 16:35:32 +02:00
Richard Davey 2087b2d76e tidying up 2013-04-26 00:24:58 +01:00
Richard Davey b2e1434f5e Tilemap collision working but needs speeding up 2013-04-25 20:05:56 +01:00
Richard Davey b8ab13fec8 Getting tilemap collision up and running 2013-04-25 01:55:56 +01:00
Richard Davey 53d8e4da2e Fixed Game.boot syntax error. 2013-04-24 09:37:29 +01:00
Richard Davey 33882ae5d1 Small readme update. 2013-04-24 02:57:49 +01:00
Richard Davey 3898faf17e New v0.9.3 release - see the changelog in the README for full details. 2013-04-24 02:48:03 +01:00
Richard Davey 1b6fbc1324 Fixed Game.boot issue and Animation issue reported in github. 2013-04-24 00:47:11 +01:00
Richard Davey 268470ef62 Added blaster example to the Test Suite and fixed a rotation bug in the particle emitter. 2013-04-24 00:18:07 +01:00
Richard Davey 6466361f5f Great new thrust ship example added for ScrollZones. Also added rotationOffset value to GameObject base class. 2013-04-23 21:27:45 +01:00
Richard Davey 00fb20f8c2 And ScrollRegions work too :) 2013-04-23 19:24:16 +01:00
Richard Davey 332f715943 Finally fixed a really annoying bug in ScrollZone and it now works perfectly across the board. 2013-04-23 15:15:34 +01:00
Richard Davey f2678104fa Saving first iteration of the ScrollZone game object. 2013-04-22 01:53:24 +01:00
Richard Davey 2638e598dc Added Stage.disablePauseScreen 2013-04-20 03:50:21 +01:00
Richard Davey 361b8e5779 Version 0.9.2 update. See the change log for full details. 2013-04-20 03:40:17 +01:00
Richard Davey 364492d786 Added grunt file and npm package for OSX debs 2013-04-20 01:24:38 +01:00
229 changed files with 68949 additions and 4655 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 612 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 809 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

+58
View File
@@ -0,0 +1,58 @@
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
typescript: {
base: {
src: ['Phaser/**/*.ts'],
dest: 'build/phaser.js',
options: {
target: 'ES5'
}
}
},
copy: {
main: {
files: [{
src: 'build/phaser.js',
dest: 'Tests/phaser.js'
}]
},
amd: {
files: [{
src: 'build/phaser.js',
dest: 'build/phaser.amd.js'
}],
options: {
processContent: function(content) {
var replacement = [
'(function (root, factory) {',
' if (typeof exports === \'object\') {',
' module.exports = factory();',
' } else if (typeof define === \'function\' && define.amd) {',
' define(factory);',
' } else {',
' root.Phaser = factory();',
' }',
'}(this, function () {',
content,
'return Phaser;',
'}));'
];
return replacement.join('\n');
}
}
}
},
watch: {
files: '**/*.ts',
tasks: ['typescript', 'copy']
}
});
grunt.registerTask('default', ['watch']);
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="Game.d.ts" />
/// <reference path="gameobjects/Sprite.d.ts" />
/// <reference path="system/animation/Animation.d.ts" />
/// <reference path="system/animation/AnimationLoader.d.ts" />
/// <reference path="system/animation/Frame.d.ts" />
/// <reference path="system/animation/FrameData.d.ts" />
module Phaser {
class AnimationManager {
constructor(game: Game, parent: Sprite);
private _game;
private _parent;
private _anims;
private _frameIndex;
private _frameData;
public currentAnim: Animation;
public currentFrame: Frame;
public loadFrameData(frameData: FrameData): void;
public add(name: string, frames?: any[], frameRate?: number, loop?: bool, useNumericIndex?: bool): void;
private validateFrames(frames, useNumericIndex);
public play(name: string, frameRate?: number, loop?: bool): void;
public stop(name: string): void;
public update(): void;
public frameData : FrameData;
public frameTotal : number;
public frame : number;
public frameName : string;
}
}
+20 -8
View File
@@ -57,6 +57,7 @@ module Phaser {
{ {
if (this.validateFrames(frames, useNumericIndex) == false) if (this.validateFrames(frames, useNumericIndex) == false)
{ {
throw Error('Invalid frames given to Animation ' + name);
return; return;
} }
} }
@@ -69,6 +70,7 @@ module Phaser {
this._anims[name] = new Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop); this._anims[name] = new Animation(this._game, this._parent, this._frameData, name, frames, frameRate, loop);
this.currentAnim = this._anims[name]; this.currentAnim = this._anims[name];
this.currentFrame = this.currentAnim.currentFrame;
} }
@@ -100,8 +102,18 @@ module Phaser {
if (this._anims[name]) if (this._anims[name])
{ {
this.currentAnim = this._anims[name]; if (this.currentAnim == this._anims[name])
this.currentAnim.play(frameRate, loop); {
if (this.currentAnim.isPlaying == false)
{
this.currentAnim.play(frameRate, loop);
}
}
else
{
this.currentAnim = this._anims[name];
this.currentAnim.play(frameRate, loop);
}
} }
} }
@@ -141,10 +153,10 @@ module Phaser {
public set frame(value: number) { public set frame(value: number) {
this.currentFrame = this._frameData.getFrame(value); if (this._frameData.getFrame(value) !== null)
if (this.currentFrame !== null)
{ {
this.currentFrame = this._frameData.getFrame(value);
this._parent.bounds.width = this.currentFrame.width; this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height; this._parent.bounds.height = this.currentFrame.height;
this._frameIndex = value; this._frameIndex = value;
@@ -158,10 +170,10 @@ module Phaser {
public set frameName(value: string) { public set frameName(value: string) {
this.currentFrame = this._frameData.getFrameByName(value); if (this._frameData.getFrameByName(value) !== null)
if (this.currentFrame !== null)
{ {
this.currentFrame = this._frameData.getFrameByName(value);
this._parent.bounds.width = this.currentFrame.width; this._parent.bounds.width = this.currentFrame.width;
this._parent.bounds.height = this.currentFrame.height; this._parent.bounds.height = this.currentFrame.height;
this._frameIndex = this.currentFrame.index; this._frameIndex = this.currentFrame.index;
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="Game.d.ts" />
module Phaser {
class Basic {
constructor(game: Game);
public _game: Game;
public name: string;
public ID: number;
public isGroup: bool;
public exists: bool;
public active: bool;
public visible: bool;
public alive: bool;
public ignoreDrawDebug: bool;
public destroy(): void;
public preUpdate(): void;
public update(): void;
public postUpdate(): void;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void;
public kill(): void;
public revive(): void;
public toString(): string;
}
}
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="Game.d.ts" />
module Phaser {
class Cache {
constructor(game: Game);
private _game;
private _canvases;
private _images;
private _sounds;
private _text;
public addCanvas(key: string, canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): void;
public addSpriteSheet(key: string, url: string, data, frameWidth: number, frameHeight: number, frameMax: number): void;
public addTextureAtlas(key: string, url: string, data, jsonData): void;
public addImage(key: string, url: string, data): void;
public addSound(key: string, url: string, data): void;
public decodedSound(key: string, data): void;
public addText(key: string, url: string, data): void;
public getCanvas(key: string);
public getImage(key: string);
public getFrameData(key: string): FrameData;
public getSound(key: string);
public isSoundDecoded(key: string): bool;
public isSpriteSheet(key: string): bool;
public getText(key: string);
public destroy(): void;
}
}
+17
View File
@@ -0,0 +1,17 @@
/// <reference path="Game.d.ts" />
/// <reference path="system/Camera.d.ts" />
module Phaser {
class CameraManager {
constructor(game: Game, x: number, y: number, width: number, height: number);
private _game;
private _cameras;
private _cameraInstance;
public current: Camera;
public getAll(): Camera[];
public update(): void;
public render(): void;
public addCamera(x: number, y: number, width: number, height: number): Camera;
public removeCamera(id: number): bool;
public destroy(): void;
}
}
+16 -13
View File
@@ -26,8 +26,8 @@ module Phaser {
} }
private _game: Game; private _game: Game;
private _cameras: Camera[]; private _cameras: Camera[];
private _cameraInstance: number = 0;
public current: Camera; public current: Camera;
@@ -45,32 +45,35 @@ module Phaser {
public addCamera(x: number, y: number, width: number, height: number): Camera { public addCamera(x: number, y: number, width: number, height: number): Camera {
var newCam: Camera = new Camera(this._game, this._cameras.length, x, y, width, height); var newCam: Camera = new Camera(this._game, this._cameraInstance, x, y, width, height);
this._cameras.push(newCam); this._cameras.push(newCam);
this._cameraInstance++;
return newCam; return newCam;
} }
public removeCamera(id: number): bool { public removeCamera(id: number): bool {
if (this._cameras[id]) for (var c = 0; c < this._cameras.length; c++)
{ {
if (this.current === this._cameras[id]) if (this._cameras[c].ID == id)
{ {
this.current = null; if (this.current.ID === this._cameras[c].ID)
{
this.current = null;
}
this._cameras.splice(c, 1);
return true;
} }
this._cameras.splice(id, 1);
return true;
}
else
{
return false;
} }
return false;
} }
public destroy() { public destroy() {
+53
View File
@@ -0,0 +1,53 @@
/// <reference path="Game.d.ts" />
/// <reference path="geom/Point.d.ts" />
/// <reference path="geom/Rectangle.d.ts" />
/// <reference path="geom/Quad.d.ts" />
/// <reference path="geom/Circle.d.ts" />
/// <reference path="geom/Line.d.ts" />
/// <reference path="geom/IntersectResult.d.ts" />
/// <reference path="system/QuadTree.d.ts" />
module Phaser {
class Collision {
constructor(game: Game);
private _game;
static LEFT: number;
static RIGHT: number;
static UP: number;
static DOWN: number;
static NONE: number;
static CEILING: number;
static FLOOR: number;
static WALL: number;
static ANY: number;
static OVERLAP_BIAS: number;
static TILE_OVERLAP: bool;
static _tempBounds: Quad;
static lineToLine(line1: Line, line2: Line, output?: IntersectResult): IntersectResult;
static lineToLineSegment(line: Line, seg: Line, output?: IntersectResult): IntersectResult;
static lineToRawSegment(line: Line, x1: number, y1: number, x2: number, y2: number, output?: IntersectResult): IntersectResult;
static lineToRay(line1: Line, ray: Line, output?: IntersectResult): IntersectResult;
static lineToCircle(line: Line, circle: Circle, output?: IntersectResult): IntersectResult;
static lineToRectangle(line: Line, rect: Rectangle, output?: IntersectResult): IntersectResult;
static lineSegmentToLineSegment(line1: Line, line2: Line, output?: IntersectResult): IntersectResult;
static lineSegmentToRay(line: Line, ray: Line, output?: IntersectResult): IntersectResult;
static lineSegmentToCircle(seg: Line, circle: Circle, output?: IntersectResult): IntersectResult;
static lineSegmentToRectangle(seg: Line, rect: Rectangle, output?: IntersectResult): IntersectResult;
static rayToRectangle(ray: Line, rect: Rectangle, output?: IntersectResult): IntersectResult;
static rayToLineSegment(rayX1, rayY1, rayX2, rayY2, lineX1, lineY1, lineX2, lineY2, output?: IntersectResult): IntersectResult;
static pointToRectangle(point, rect: Rectangle, output?: IntersectResult): IntersectResult;
static rectangleToRectangle(rect1: Rectangle, rect2: Rectangle, output?: IntersectResult): IntersectResult;
static rectangleToCircle(rect: Rectangle, circle: Circle, output?: IntersectResult): IntersectResult;
static circleToCircle(circle1: Circle, circle2: Circle, output?: IntersectResult): IntersectResult;
static circleToRectangle(circle: Circle, rect: Rectangle, output?: IntersectResult): IntersectResult;
static circleContainsPoint(circle: Circle, point, output?: IntersectResult): IntersectResult;
public overlap(object1?: Basic, object2?: Basic, notifyCallback?, processCallback?): bool;
static separate(object1, object2): bool;
static separateTile(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool, collideUp: bool, collideDown: bool): bool;
static separateTileX(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideLeft: bool, collideRight: bool): bool;
static separateTileY(object: GameObject, x: number, y: number, width: number, height: number, mass: number, collideUp: bool, collideDown: bool): bool;
static separateX(object1, object2): bool;
static separateY(object1, object2): bool;
static distance(x1: number, y1: number, x2: number, y2: number): number;
static distanceSquared(x1: number, y1: number, x2: number, y2: number): number;
}
}
+550 -387
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
/// <reference path="Game.d.ts" />
module Phaser {
class DynamicTexture {
constructor(game: Game, width: number, height: number);
private _game;
private _sx;
private _sy;
private _sw;
private _sh;
private _dx;
private _dy;
private _dw;
private _dh;
public bounds: Rectangle;
public canvas: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
public getPixel(x: number, y: number): number;
public getPixel32(x: number, y: number): number;
public getPixels(rect: Rectangle): ImageData;
public setPixel(x: number, y: number, color: number): void;
public setPixel32(x: number, y: number, color: number): void;
public setPixels(rect: Rectangle, input): void;
public fillRect(rect: Rectangle, color: number): void;
public pasteImage(key: string, frame?: number, destX?: number, destY?: number, destWidth?: number, destHeight?: number): void;
public copyPixels(sourceTexture: DynamicTexture, sourceRect: Rectangle, destPoint: Point): void;
public clear(): void;
public width : number;
public height : number;
private getColor32(alpha, red, green, blue);
private getColor(red, green, blue);
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ module Phaser {
export class DynamicTexture { export class DynamicTexture {
constructor(game: Game, key: string, width: number, height: number) { constructor(game: Game, width: number, height: number) {
this._game = game; this._game = game;
+18
View File
@@ -0,0 +1,18 @@
/// <reference path="Game.d.ts" />
module Phaser {
class FXManager {
constructor(game: Game);
private _fx;
private _length;
private _game;
public active: bool;
public visible: bool;
public add(effect): any;
public preUpdate(): void;
public postUpdate(): void;
public preRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void;
public render(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void;
public postRender(camera: Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number): void;
public destroy(): void;
}
}
+220
View File
@@ -0,0 +1,220 @@
/// <reference path="Game.ts" />
/**
* Phaser - FXManager
*
* The FXManager controls all special effects applied to game objects such as Cameras.
*/
module Phaser {
export class FXManager {
constructor(game: Game, parent) {
this._game = game;
this._parent = parent;
this._fx = [];
this.active = true;
this.visible = true;
}
/**
* The essential reference to the main game object.
*/
private _game: Game;
/**
* A reference to the object that owns this FXManager instance.
*/
private _parent;
/**
* The array in which we keep all of the registered FX
*/
private _fx;
/**
* Holds the size of the _fx array
*/
private _length: number;
/**
* Controls whether any of the FX have preUpdate, update or postUpdate called
*/
public active: bool;
/**
* Controls whether any of the FX have preRender, render or postRender called
*/
public visible: bool;
/**
* Adds a new FX to the FXManager.
* The effect must be an object with at least one of the following methods: preUpdate, postUpdate, preRender, render or postRender.
* A new instance of the effect will be created and a reference to Game will be passed to the object constructor.
*/
public add(effect): any {
var result: bool = 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;
}
}
/**
* Pre-update is called at the start of the objects update cycle, before any other updates have taken place.
*/
public preUpdate() {
if (this.active)
{
for (var i = 0; i < this._length; i++)
{
if (this._fx[i].preUpdate)
{
this._fx[i].effect.preUpdate();
}
}
}
}
/**
* Post-update is called at the end of the objects update cycle, after other update logic has taken place.
*/
public postUpdate() {
if (this.active)
{
for (var i = 0; i < this._length; i++)
{
if (this._fx[i].postUpdate)
{
this._fx[i].effect.postUpdate();
}
}
}
}
/**
* Pre-render is called at the start of the object render cycle, before any transforms have taken place.
* It happens directly AFTER a canvas context.save has happened if added to a Camera.
*/
public preRender(camera:Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) {
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);
}
}
}
}
/**
* render is called during the objects render cycle, right after all transforms have finished, but before any children/image data is rendered.
*/
public render(camera:Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) {
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);
}
}
}
}
/**
* Post-render is called during the objects render cycle, after the children/image data has been rendered.
* It happens directly BEFORE a canvas context.restore has happened if added to a Camera.
*/
public postRender(camera:Camera, cameraX: number, cameraY: number, cameraWidth: number, cameraHeight: number) {
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);
}
}
}
}
/**
* Clear down this FXManager and null out references
*/
public destroy() {
this._game = null;
this._fx = null;
}
}
}
+88
View File
@@ -0,0 +1,88 @@
/// <reference path="AnimationManager.d.ts" />
/// <reference path="Basic.d.ts" />
/// <reference path="Cache.d.ts" />
/// <reference path="CameraManager.d.ts" />
/// <reference path="Collision.d.ts" />
/// <reference path="DynamicTexture.d.ts" />
/// <reference path="FXManager.d.ts" />
/// <reference path="GameMath.d.ts" />
/// <reference path="Group.d.ts" />
/// <reference path="Loader.d.ts" />
/// <reference path="Motion.d.ts" />
/// <reference path="Signal.d.ts" />
/// <reference path="SignalBinding.d.ts" />
/// <reference path="SoundManager.d.ts" />
/// <reference path="Stage.d.ts" />
/// <reference path="Time.d.ts" />
/// <reference path="TweenManager.d.ts" />
/// <reference path="World.d.ts" />
/// <reference path="system/Device.d.ts" />
/// <reference path="system/RandomDataGenerator.d.ts" />
/// <reference path="system/RequestAnimationFrame.d.ts" />
/// <reference path="system/input/Input.d.ts" />
/// <reference path="system/input/Keyboard.d.ts" />
/// <reference path="system/input/Mouse.d.ts" />
/// <reference path="system/input/Touch.d.ts" />
/// <reference path="gameobjects/Emitter.d.ts" />
/// <reference path="gameobjects/GameObject.d.ts" />
/// <reference path="gameobjects/GeomSprite.d.ts" />
/// <reference path="gameobjects/Particle.d.ts" />
/// <reference path="gameobjects/Sprite.d.ts" />
/// <reference path="gameobjects/Tilemap.d.ts" />
/// <reference path="gameobjects/ScrollZone.d.ts" />
module Phaser {
class Game {
constructor(callbackContext, parent?: string, width?: number, height?: number, initCallback?, createCallback?, updateCallback?, renderCallback?);
private _raf;
private _maxAccumulation;
private _accumulator;
private _step;
private _loadComplete;
private _paused;
private _pendingState;
public callbackContext;
public onInitCallback;
public onCreateCallback;
public onUpdateCallback;
public onRenderCallback;
public onPausedCallback;
public cache: Cache;
public collision: Collision;
public input: Input;
public loader: Loader;
public math: GameMath;
public motion: Motion;
public sound: SoundManager;
public stage: Stage;
public time: Time;
public tweens: TweenManager;
public world: World;
public rnd: RandomDataGenerator;
public device: Device;
public isBooted: bool;
public isRunning: bool;
private boot(parent, width, height);
private loadComplete();
private bootLoop();
private pausedLoop();
private loop();
private startState();
public setCallbacks(initCallback?, createCallback?, updateCallback?, renderCallback?): void;
public switchState(state, clearWorld?: bool, clearCache?: bool): void;
public destroy(): void;
public paused : bool;
public framerate : number;
public createCamera(x: number, y: number, width: number, height: number): Camera;
public createGeomSprite(x: number, y: number): GeomSprite;
public createSprite(x: number, y: number, key?: string): Sprite;
public createDynamicTexture(width: number, height: number): DynamicTexture;
public createGroup(MaxSize?: number): Group;
public createParticle(): Particle;
public createEmitter(x?: number, y?: number, size?: number): Emitter;
public createScrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone;
public createTilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap;
public createTween(obj): Tween;
public collide(objectOrGroup1?: Basic, objectOrGroup2?: Basic, notifyCallback?): bool;
public camera : Camera;
}
}
+78 -28
View File
@@ -4,6 +4,7 @@
/// <reference path="CameraManager.ts" /> /// <reference path="CameraManager.ts" />
/// <reference path="Collision.ts" /> /// <reference path="Collision.ts" />
/// <reference path="DynamicTexture.ts" /> /// <reference path="DynamicTexture.ts" />
/// <reference path="FXManager.ts" />
/// <reference path="GameMath.ts" /> /// <reference path="GameMath.ts" />
/// <reference path="Group.ts" /> /// <reference path="Group.ts" />
/// <reference path="Loader.ts" /> /// <reference path="Loader.ts" />
@@ -28,12 +29,16 @@
/// <reference path="gameobjects/Particle.ts" /> /// <reference path="gameobjects/Particle.ts" />
/// <reference path="gameobjects/Sprite.ts" /> /// <reference path="gameobjects/Sprite.ts" />
/// <reference path="gameobjects/Tilemap.ts" /> /// <reference path="gameobjects/Tilemap.ts" />
/// <reference path="gameobjects/ScrollZone.ts" />
/** /**
* Phaser - Game * Phaser - Game
* *
* This is where the magic happens. The Game object is the heart of your game, providing quick access to common * This is where the magic happens. The Game object is the heart of your game,
* functions and handling the boot process. * providing quick access to common functions and handling the boot process.
*
* "Hell, there are no rules here - we're trying to accomplish something."
* Thomas A. Edison
*/ */
module Phaser { module Phaser {
@@ -50,11 +55,12 @@ module Phaser {
if (document.readyState === 'complete' || document.readyState === 'interactive') if (document.readyState === 'complete' || document.readyState === 'interactive')
{ {
this.boot(parent, width, height); setTimeout(() => this.boot(parent, width, height));
} }
else else
{ {
document.addEventListener('DOMContentLoaded', () => this.boot(parent, width, height), false); document.addEventListener('DOMContentLoaded', () => this.boot(parent, width, height), false);
window.addEventListener('load', () => this.boot(parent, width, height), false);
} }
} }
@@ -75,7 +81,6 @@ module Phaser {
public onRenderCallback = null; public onRenderCallback = null;
public onPausedCallback = null; public onPausedCallback = null;
public camera: Camera; // quick reference to the default created camera, access the rest via .world
public cache: Cache; public cache: Cache;
public collision: Collision; public collision: Collision;
public input: Input; public input: Input;
@@ -91,9 +96,15 @@ module Phaser {
public device: Device; public device: Device;
public isBooted: bool = false; public isBooted: bool = false;
public isRunning: bool = false;
private boot(parent: string, width: number, height: number) { private boot(parent: string, width: number, height: number) {
if (this.isBooted == true)
{
return;
}
if (!document.body) if (!document.body)
{ {
window.setTimeout(() => this.boot(parent, width, height), 13); window.setTimeout(() => this.boot(parent, width, height), 13);
@@ -115,16 +126,16 @@ module Phaser {
this.rnd = new RandomDataGenerator([(Date.now() * Math.random()).toString()]); this.rnd = new RandomDataGenerator([(Date.now() * Math.random()).toString()]);
this.framerate = 60; this.framerate = 60;
this.isBooted = true;
// Display the default game screen? // Display the default game screen?
if (this.onInitCallback == null && this.onCreateCallback == null && this.onUpdateCallback == null && this.onRenderCallback == null && this._pendingState == null) if (this.onInitCallback == null && this.onCreateCallback == null && this.onUpdateCallback == null && this.onRenderCallback == null && this._pendingState == null)
{ {
this.isBooted = false; this._raf = new RequestAnimationFrame(this.bootLoop, this);
this.stage.drawInitScreen();
} }
else else
{ {
this.isBooted = true; this.isRunning = true;
this._loadComplete = false; this._loadComplete = false;
this._raf = new RequestAnimationFrame(this.loop, this); this._raf = new RequestAnimationFrame(this.loop, this);
@@ -151,22 +162,33 @@ module Phaser {
} }
private bootLoop() {
this.time.update();
this.tweens.update();
this.input.update();
this.stage.update();
}
private pausedLoop() {
this.time.update();
this.tweens.update();
this.input.update();
this.stage.update();
if (this.onPausedCallback !== null)
{
this.onPausedCallback.call(this.callbackContext);
}
}
private loop() { private loop() {
this.time.update(); this.time.update();
this.tweens.update(); this.tweens.update();
if (this._paused == true)
{
if (this.onPausedCallback !== null)
{
this.onPausedCallback.call(this.callbackContext);
}
return;
}
this.input.update(); this.input.update();
this.stage.update(); this.stage.update();
@@ -202,7 +224,20 @@ module Phaser {
if (this.onInitCallback !== null) if (this.onInitCallback !== null)
{ {
this.loader.reset();
this.onInitCallback.call(this.callbackContext); this.onInitCallback.call(this.callbackContext);
// Is the loader empty?
if (this.loader.queueSize == 0)
{
if (this.onCreateCallback !== null)
{
this.onCreateCallback.call(this.callbackContext);
}
this._loadComplete = true;
}
} }
else else
{ {
@@ -293,8 +328,7 @@ module Phaser {
} }
else else
{ {
throw Error("Invalid State object given. Must contain at least a create or update function."); throw new Error("Invalid State object given. Must contain at least a create or update function.");
return;
} }
} }
@@ -308,7 +342,6 @@ module Phaser {
this.onUpdateCallback = null; this.onUpdateCallback = null;
this.onRenderCallback = null; this.onRenderCallback = null;
this.onPausedCallback = null; this.onPausedCallback = null;
this.camera = null;
this.cache = null; this.cache = null;
this.input = null; this.input = null;
this.loader = null; this.loader = null;
@@ -329,12 +362,21 @@ module Phaser {
if (value == true && this._paused == false) if (value == true && this._paused == false)
{ {
this._paused = true; this._paused = true;
this._raf.setCallback(this.pausedLoop);
} }
else if (value == false && this._paused == true) else if (value == false && this._paused == true)
{ {
this._paused = false; this._paused = false;
this.time.time = Date.now(); this.time.time = Date.now();
this.input.reset(); this.input.reset();
if (this.isRunning == false)
{
this._raf.setCallback(this.bootLoop);
}
else
{
this._raf.setCallback(this.loop);
}
} }
} }
@@ -368,8 +410,8 @@ module Phaser {
return this.world.createSprite(x, y, key); return this.world.createSprite(x, y, key);
} }
public createDynamicTexture(key: string, width: number, height: number): DynamicTexture { public createDynamicTexture(width: number, height: number): DynamicTexture {
return this.world.createDynamicTexture(key, width, height); return this.world.createDynamicTexture(width, height);
} }
public createGroup(MaxSize?: number = 0): Group { public createGroup(MaxSize?: number = 0): Group {
@@ -384,16 +426,24 @@ module Phaser {
return this.world.createEmitter(x, y, size); return this.world.createEmitter(x, y, size);
} }
public createTilemap(key: string, mapData: string, format: number, tileWidth?: number, tileHeight?: number): Tilemap { public createScrollZone(key: string, x?: number = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone {
return this.world.createTilemap(key, mapData, format, tileWidth, tileHeight); return this.world.createScrollZone(key, x, y, width, height);
}
public createTilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap {
return this.world.createTilemap(key, mapData, format, resizeWorld, tileWidth, tileHeight);
} }
public createTween(obj): Tween { public createTween(obj): Tween {
return this.tweens.create(obj); return this.tweens.create(obj);
} }
public collide(ObjectOrGroup1: Basic = null, ObjectOrGroup2: Basic = null, NotifyCallback = null): bool { public collide(objectOrGroup1: Basic = null, objectOrGroup2: Basic = null, notifyCallback = null): bool {
return this.collision.overlap(ObjectOrGroup1, ObjectOrGroup2, NotifyCallback, Collision.separate); return this.collision.overlap(objectOrGroup1, objectOrGroup2, notifyCallback, Collision.separate);
}
public get camera(): Camera {
return this.world.cameras.current;
} }
} }
+110
View File
@@ -0,0 +1,110 @@
/// <reference path="Game.d.ts" />
module Phaser {
class GameMath {
constructor(game: Game);
private _game;
static PI: number;
static PI_2: number;
static PI_4: number;
static PI_8: number;
static PI_16: number;
static TWO_PI: number;
static THREE_PI_2: number;
static E: number;
static LN10: number;
static LN2: number;
static LOG10E: number;
static LOG2E: number;
static SQRT1_2: number;
static SQRT2: number;
static DEG_TO_RAD: number;
static RAD_TO_DEG: number;
static B_16: number;
static B_31: number;
static B_32: number;
static B_48: number;
static B_53: number;
static B_64: number;
static ONE_THIRD: number;
static TWO_THIRDS: number;
static ONE_SIXTH: number;
static COS_PI_3: number;
static SIN_2PI_3: number;
static CIRCLE_ALPHA: number;
static ON: bool;
static OFF: bool;
static SHORT_EPSILON: number;
static PERC_EPSILON: number;
static EPSILON: number;
static LONG_EPSILON: number;
public cosTable: any[];
public sinTable: any[];
public fuzzyEqual(a: number, b: number, epsilon?: number): bool;
public fuzzyLessThan(a: number, b: number, epsilon?: number): bool;
public fuzzyGreaterThan(a: number, b: number, epsilon?: number): bool;
public fuzzyCeil(val: number, epsilon?: number): number;
public fuzzyFloor(val: number, epsilon?: number): number;
public average(...args: any[]): number;
public slam(value: number, target: number, epsilon?: number): number;
public percentageMinMax(val: number, max: number, min?: number): number;
public sign(n: number): number;
public truncate(n: number): number;
public shear(n: number): number;
public wrap(val: number, max: number, min?: number): number;
public arithWrap(value: number, max: number, min?: number): number;
public clamp(input: number, max: number, min?: number): number;
public snapTo(input: number, gap: number, start?: number): number;
public snapToFloor(input: number, gap: number, start?: number): number;
public snapToCeil(input: number, gap: number, start?: number): number;
public snapToInArray(input: number, arr: number[], sort?: bool): number;
public roundTo(value: number, place?: number, base?: number): number;
public floorTo(value: number, place?: number, base?: number): number;
public ceilTo(value: number, place?: number, base?: number): number;
public interpolateFloat(a: number, b: number, weight: number): number;
public radiansToDegrees(angle: number): number;
public degreesToRadians(angle: number): number;
public angleBetween(x1: number, y1: number, x2: number, y2: number): number;
public normalizeAngle(angle: number, radians?: bool): number;
public nearestAngleBetween(a1: number, a2: number, radians?: bool): number;
public normalizeAngleToAnother(dep: number, ind: number, radians?: bool): number;
public normalizeAngleAfterAnother(dep: number, ind: number, radians?: bool): number;
public normalizeAngleBeforeAnother(dep: number, ind: number, radians?: bool): number;
public interpolateAngles(a1: number, a2: number, weight: number, radians?: bool, ease?): number;
public logBaseOf(value: number, base: number): number;
public GCD(m: number, n: number): number;
public LCM(m: number, n: number): number;
public factorial(value: number): number;
public gammaFunction(value: number): number;
public fallingFactorial(base: number, exp: number): number;
public risingFactorial(base: number, exp: number): number;
public binCoef(n: number, k: number): number;
public risingBinCoef(n: number, k: number): number;
public chanceRoll(chance?: number): bool;
public maxAdd(value: number, amount: number, max: number): number;
public minSub(value: number, amount: number, min: number): number;
public wrapValue(value: number, amount: number, max: number): number;
public randomSign(): number;
public isOdd(n: number): bool;
public isEven(n: number): bool;
public wrapAngle(angle: number): number;
public angleLimit(angle: number, min: number, max: number): number;
public linearInterpolation(v, k);
public bezierInterpolation(v, k): number;
public catmullRomInterpolation(v, k);
public linear(p0, p1, t);
public bernstein(n, i): number;
public catmullRom(p0, p1, p2, p3, t);
public difference(a: number, b: number): number;
public globalSeed: number;
public random(): number;
public srand(Seed: number): number;
public getRandom(Objects, StartIndex?: number, Length?: number);
public floor(Value: number): number;
public ceil(Value: number): number;
public sinCosGenerator(length: number, sinAmplitude?: number, cosAmplitude?: number, frequency?: number): any[];
public shiftSinTable(): number;
public shiftCosTable(): number;
public vectorLength(dx: number, dy: number): number;
public dotProduct(ax: number, ay: number, bx: number, by: number): number;
}
}
+41 -11
View File
@@ -855,29 +855,27 @@ module Phaser {
/** /**
* Fetch a random entry from the given array. * Fetch a random entry from the given array.
* Will return null if random selection is missing, or array has no entries. * Will return null if random selection is missing, or array has no entries.
* <code>G.getRandom()</code> is deterministic and safe for use with replays/recordings.
* HOWEVER, <code>U.getRandom()</code> is NOT deterministic and unsafe for use with replays/recordings.
* *
* @param Objects An array of objects. * @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 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. * @param length Optional restriction on the number of values you want to randomly select from.
* *
* @return The random object that was selected. * @return The random object that was selected.
*/ */
public getRandom(Objects, StartIndex: number = 0, Length: number = 0) { public getRandom(objects, startIndex: number = 0, length: number = 0) {
if (Objects != null) if (objects != null)
{ {
var l: number = Length; var l: number = length;
if ((l == 0) || (l > Objects.length - StartIndex)) if ((l == 0) || (l > objects.length - startIndex))
{ {
l = Objects.length - StartIndex; l = objects.length - startIndex;
} }
if (l > 0) if (l > 0)
{ {
return Objects[StartIndex + Math.floor(Math.random() * l)]; return objects[startIndex + Math.floor(Math.random() * l)];
} }
} }
@@ -943,6 +941,38 @@ module Phaser {
return this.sinTable; return this.sinTable;
}
/**
* 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.
*/
public shiftSinTable(): number {
if (this.sinTable)
{
var s = this.sinTable.shift();
this.sinTable.push(s);
return s;
}
}
/**
* 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.
*/
public shiftCosTable(): number {
if (this.cosTable)
{
var s = this.cosTable.shift();
this.cosTable.push(s);
return s;
}
} }
/** /**
+39
View File
@@ -0,0 +1,39 @@
/// <reference path="Basic.d.ts" />
/// <reference path="Game.d.ts" />
module Phaser {
class Group extends Basic {
constructor(game: Game, MaxSize?: number);
static ASCENDING: number;
static DESCENDING: number;
public members: Basic[];
public length: number;
private _maxSize;
private _marker;
private _sortIndex;
private _sortOrder;
public destroy(): void;
public update(): void;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void;
public maxSize : number;
public add(Object: Basic): Basic;
public recycle(ObjectClass?);
public remove(Object: Basic, Splice?: bool): Basic;
public replace(OldObject: Basic, NewObject: Basic): Basic;
public sort(Index?: string, Order?: number): void;
public setAll(VariableName: string, Value: Object, Recurse?: bool): void;
public callAll(FunctionName: string, Recurse?: bool): void;
public forEach(callback, recursive?: bool): void;
public forEachAlive(context, callback, recursive?: bool): void;
public getFirstAvailable(ObjectClass?);
public getFirstNull(): number;
public getFirstExtant(): Basic;
public getFirstAlive(): Basic;
public getFirstDead(): Basic;
public countLiving(): number;
public countDead(): number;
public getRandom(StartIndex?: number, Length?: number): Basic;
public clear(): void;
public kill(): void;
public sortHandler(Obj1: Basic, Obj2: Basic): number;
}
}
+45 -21
View File
@@ -286,7 +286,7 @@ module Phaser {
return null; return null;
} }
return this.add(new ObjectClass()); return this.add(new ObjectClass(this._game));
} }
else else
{ {
@@ -314,28 +314,28 @@ module Phaser {
return null; return null;
} }
return this.add(new ObjectClass()); return this.add(new ObjectClass(this._game));
} }
} }
/** /**
* Removes an object from the group. * Removes an object from the group.
* *
* @param Object The <code>Basic</code> you want to remove. * @param object The <code>Basic</code> you want to remove.
* @param Splice Whether the object should be cut from the array entirely or not. * @param splice Whether the object should be cut from the array entirely or not.
* *
* @return The removed object. * @return The removed object.
*/ */
public remove(Object: Basic, Splice: bool = false): Basic { public remove(object: Basic, splice: bool = false): Basic {
var index: number = this.members.indexOf(Object); var index: number = this.members.indexOf(object);
if ((index < 0) || (index >= this.members.length)) if ((index < 0) || (index >= this.members.length))
{ {
return null; return null;
} }
if (Splice) if (splice)
{ {
this.members.splice(index, 1); this.members.splice(index, 1);
this.length--; this.length--;
@@ -345,30 +345,30 @@ module Phaser {
this.members[index] = null; this.members[index] = null;
} }
return Object; return object;
} }
/** /**
* Replaces an existing <code>Basic</code> with a new one. * Replaces an existing <code>Basic</code> with a new one.
* *
* @param OldObject The object you want to replace. * @param oldObject The object you want to replace.
* @param NewObject The new object you want to use instead. * @param newObject The new object you want to use instead.
* *
* @return The new object. * @return The new object.
*/ */
public replace(OldObject: Basic, NewObject: Basic): Basic { public replace(oldObject: Basic, newObject: Basic): Basic {
var index: number = this.members.indexOf(OldObject); var index: number = this.members.indexOf(oldObject);
if ((index < 0) || (index >= this.members.length)) if ((index < 0) || (index >= this.members.length))
{ {
return null; return null;
} }
this.members[index] = NewObject; this.members[index] = newObject;
return NewObject; return newObject;
} }
@@ -379,13 +379,13 @@ module Phaser {
* <code>State.update()</code> override. To sort all existing objects after * <code>State.update()</code> override. To sort all existing objects after
* a big explosion or bomb attack, you might call <code>myGroup.sort("exists",Group.DESCENDING)</code>. * a big explosion or bomb attack, you might call <code>myGroup.sort("exists",Group.DESCENDING)</code>.
* *
* @param Index The <code>string</code> name of the member variable you want to sort on. Default value is "y". * @param index The <code>string</code> name of the member variable you want to sort on. Default value is "y".
* @param Order A <code>Group</code> constant that defines the sort order. Possible values are <code>Group.ASCENDING</code> and <code>Group.DESCENDING</code>. Default value is <code>Group.ASCENDING</code>. * @param order A <code>Group</code> constant that defines the sort order. Possible values are <code>Group.ASCENDING</code> and <code>Group.DESCENDING</code>. Default value is <code>Group.ASCENDING</code>.
*/ */
public sort(Index: string = "y", Order: number = Group.ASCENDING) { public sort(index: string = "y", order: number = Group.ASCENDING) {
this._sortIndex = Index; this._sortIndex = index;
this._sortOrder = Order; this._sortOrder = order;
this.members.sort(this.sortHandler); this.members.sort(this.sortHandler);
} }
@@ -450,7 +450,7 @@ module Phaser {
} }
} }
public forEach(callback, Recurse: bool = false) { public forEach(callback, recursive: bool = false) {
var basic; var basic;
var i: number = 0; var i: number = 0;
@@ -461,7 +461,7 @@ module Phaser {
if (basic != null) if (basic != null)
{ {
if (Recurse && (basic.isGroup == true)) if (recursive && (basic.isGroup == true))
{ {
basic.forEach(callback, true); basic.forEach(callback, true);
} }
@@ -474,6 +474,30 @@ module Phaser {
} }
public forEachAlive(context, callback, recursive: bool = false) {
var basic;
var i: number = 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);
}
}
}
}
/** /**
* Call this function to retrieve the first object with exists == false in the group. * 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. * This is handy for recycling in general, e.g. respawning enemies.
+34
View File
@@ -0,0 +1,34 @@
/// <reference path="Game.d.ts" />
module Phaser {
class Loader {
constructor(game: Game, callback);
private _game;
private _keys;
private _fileList;
private _gameCreateComplete;
private _onComplete;
private _onFileLoad;
private _progressChunk;
private _xhr;
private _queueSize;
public hasLoaded: bool;
public progress: number;
public reset(): void;
public queueSize : number;
public addImageFile(key: string, url: string): void;
public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, frameMax?: number): void;
public addTextureAtlas(key: string, url: string, jsonURL?: string, jsonData?): void;
public addAudioFile(key: string, url: string): void;
public addTextFile(key: string, url: string): void;
public removeFile(key: string): void;
public removeAll(): void;
public load(onFileLoadCallback?, onCompleteCallback?): void;
private loadFile();
private fileError(key);
private fileComplete(key);
private jsonLoadComplete(key);
private jsonLoadError(key);
private nextFile(previousKey, success);
private checkKeyExists(key);
}
}
+33 -26
View File
@@ -18,6 +18,7 @@ module Phaser {
this._keys = []; this._keys = [];
this._fileList = {}; this._fileList = {};
this._xhr = new XMLHttpRequest(); this._xhr = new XMLHttpRequest();
this._queueSize = 0;
} }
@@ -29,20 +30,18 @@ module Phaser {
private _onFileLoad; private _onFileLoad;
private _progressChunk: number; private _progressChunk: number;
private _xhr: XMLHttpRequest; private _xhr: XMLHttpRequest;
private _queueSize: number;
public hasLoaded: bool; public hasLoaded: bool;
public progress: number; public progress: number;
private checkKeyExists(key: string): bool { public reset() {
this._queueSize = 0;
}
if (this._fileList[key]) public get queueSize(): number {
{
return true; return this._queueSize;
}
else
{
return false;
}
} }
@@ -50,6 +49,7 @@ module Phaser {
if (this.checkKeyExists(key) === false) if (this.checkKeyExists(key) === false)
{ {
this._queueSize++;
this._fileList[key] = { type: 'image', key: key, url: url, data: null, error: false, loaded: false }; this._fileList[key] = { type: 'image', key: key, url: url, data: null, error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -60,6 +60,7 @@ module Phaser {
if (this.checkKeyExists(key) === false) 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._fileList[key] = { type: 'spritesheet', key: key, url: url, data: null, frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -68,15 +69,12 @@ module Phaser {
public addTextureAtlas(key: string, url: string, jsonURL?: string = null, jsonData? = null) { public addTextureAtlas(key: string, url: string, jsonURL?: string = null, jsonData? = null) {
//console.log('addTextureAtlas');
//console.log(typeof jsonData);
if (this.checkKeyExists(key) === false) if (this.checkKeyExists(key) === false)
{ {
if (jsonURL !== null) if (jsonURL !== null)
{ {
//console.log('A URL to a json file has been given');
// A URL to a json file has been given // 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._fileList[key] = { type: 'textureatlas', key: key, url: url, data: null, jsonURL: jsonURL, jsonData: null, error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -85,24 +83,21 @@ module Phaser {
// A json string or object has been given // A json string or object has been given
if (typeof jsonData === 'string') if (typeof jsonData === 'string')
{ {
//console.log('A json string has been given');
var data = JSON.parse(jsonData); var data = JSON.parse(jsonData);
//console.log(data);
// Malformed? // Malformed?
if (data['frames']) if (data['frames'])
{ {
//console.log('frames array found'); this._queueSize++;
this._fileList[key] = { type: 'textureatlas', key: key, url: url, data: null, jsonURL: null, jsonData: data['frames'], error: false, loaded: false }; this._fileList[key] = { type: 'textureatlas', key: key, url: url, data: null, jsonURL: null, jsonData: data['frames'], error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
} }
else else
{ {
//console.log('A json object has been given', jsonData);
// Malformed? // Malformed?
if (jsonData['frames']) if (jsonData['frames'])
{ {
//console.log('frames array found'); this._queueSize++;
this._fileList[key] = { type: 'textureatlas', key: key, url: url, data: null, jsonURL: null, jsonData: jsonData['frames'], error: false, loaded: false }; this._fileList[key] = { type: 'textureatlas', key: key, url: url, data: null, jsonURL: null, jsonData: jsonData['frames'], error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -118,6 +113,7 @@ module Phaser {
if (this.checkKeyExists(key) === false) 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._fileList[key] = { type: 'audio', key: key, url: url, data: null, buffer: null, error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -128,6 +124,7 @@ module Phaser {
if (this.checkKeyExists(key) === false) if (this.checkKeyExists(key) === false)
{ {
this._queueSize++;
this._fileList[key] = { type: 'text', key: key, url: url, data: null, error: false, loaded: false }; this._fileList[key] = { type: 'text', key: key, url: url, data: null, error: false, loaded: false };
this._keys.push(key); this._keys.push(key);
} }
@@ -243,7 +240,6 @@ module Phaser {
break; break;
case 'textureatlas': case 'textureatlas':
//console.log('texture atlas loaded');
if (file.jsonURL == null) if (file.jsonURL == null)
{ {
this._game.cache.addTextureAtlas(file.key, file.url, file.data, file.jsonData); this._game.cache.addTextureAtlas(file.key, file.url, file.data, file.jsonData);
@@ -251,7 +247,6 @@ module Phaser {
else else
{ {
// Load the JSON before carrying on with the next file // Load the JSON before carrying on with the next file
//console.log('Loading the JSON before carrying on with the next file');
loadNext = false; loadNext = false;
this._xhr.open("GET", file.jsonURL, true); this._xhr.open("GET", file.jsonURL, true);
this._xhr.responseType = "text"; this._xhr.responseType = "text";
@@ -281,12 +276,8 @@ module Phaser {
private jsonLoadComplete(key: string) { private jsonLoadComplete(key: string) {
//console.log('json load complete');
var data = JSON.parse(this._xhr.response); var data = JSON.parse(this._xhr.response);
//console.log(data);
// Malformed? // Malformed?
if (data['frames']) if (data['frames'])
{ {
@@ -300,8 +291,6 @@ module Phaser {
private jsonLoadError(key: string) { private jsonLoadError(key: string) {
//console.log('json load error');
var file = this._fileList[key]; var file = this._fileList[key];
file.error = true; file.error = true;
this.nextFile(key, true); this.nextFile(key, true);
@@ -311,6 +300,11 @@ module Phaser {
private nextFile(previousKey: string, success: bool) { private nextFile(previousKey: string, success: bool) {
this.progress = Math.round(this.progress + this._progressChunk); this.progress = Math.round(this.progress + this._progressChunk);
if (this.progress > 1)
{
this.progress = 1;
}
if (this._onFileLoad) if (this._onFileLoad)
{ {
@@ -335,6 +329,19 @@ module Phaser {
} }
private checkKeyExists(key: string): bool {
if (this._fileList[key])
{
return true;
}
else
{
return false;
}
}
} }
} }
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="Game.d.ts" />
/// <reference path="gameobjects/GameObject.d.ts" />
module Phaser {
class Motion {
constructor(game: Game);
private _game;
public computeVelocity(Velocity: number, Acceleration?: number, Drag?: number, Max?: number): number;
public velocityFromAngle(angle: number, speed: number): Point;
public moveTowardsObject(source: GameObject, dest: GameObject, speed?: number, maxTime?: number): void;
public accelerateTowardsObject(source: GameObject, dest: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void;
public moveTowardsMouse(source: GameObject, speed?: number, maxTime?: number): void;
public accelerateTowardsMouse(source: GameObject, speed: number, xSpeedMax: number, ySpeedMax: number): void;
public moveTowardsPoint(source: GameObject, target: Point, speed?: number, maxTime?: number): void;
public accelerateTowardsPoint(source: GameObject, target: Point, speed: number, xSpeedMax: number, ySpeedMax: number): void;
public distanceBetween(a: GameObject, b: GameObject): number;
public distanceToPoint(a: GameObject, target: Point): number;
public distanceToMouse(a: GameObject): number;
public angleBetweenPoint(a: GameObject, target: Point, asDegrees?: bool): number;
public angleBetween(a: GameObject, b: GameObject, asDegrees?: bool): number;
public velocityFromFacing(parent: GameObject, speed: number): Point;
public angleBetweenMouse(a: GameObject, asDegrees?: bool): number;
}
}
+5
View File
@@ -79,6 +79,11 @@ module Phaser {
*/ */
public velocityFromAngle(angle: number, speed: number): Point { public velocityFromAngle(angle: number, speed: number): Point {
if (isNaN(speed))
{
speed = 0;
}
var a: number = this._game.math.degreesToRadians(angle); var a: number = this._game.math.degreesToRadians(angle);
return new Point((Math.cos(a) * speed), (Math.sin(a) * speed)); return new Point((Math.cos(a) * speed), (Math.sin(a) * speed));
+29 -3
View File
@@ -47,12 +47,14 @@
<TypeScriptIncludeComments>true</TypeScriptIncludeComments> <TypeScriptIncludeComments>true</TypeScriptIncludeComments>
<TypeScriptSourceMap>false</TypeScriptSourceMap> <TypeScriptSourceMap>false</TypeScriptSourceMap>
<TypeScriptOutFile>../build/phaser.js</TypeScriptOutFile> <TypeScriptOutFile>../build/phaser.js</TypeScriptOutFile>
<TypeScriptGeneratesDeclarations>true</TypeScriptGeneratesDeclarations>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'"> <PropertyGroup Condition="'$(Configuration)' == 'Release'">
<TypeScriptTarget>ES5</TypeScriptTarget> <TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptIncludeComments>false</TypeScriptIncludeComments> <TypeScriptIncludeComments>false</TypeScriptIncludeComments>
<TypeScriptSourceMap>false</TypeScriptSourceMap> <TypeScriptSourceMap>false</TypeScriptSourceMap>
<TypeScriptOutFile>../build/phaser.js</TypeScriptOutFile> <TypeScriptOutFile>../build/phaser.js</TypeScriptOutFile>
<TypeScriptGeneratesDeclarations>true</TypeScriptGeneratesDeclarations>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Folder Include="plugins\" /> <Folder Include="plugins\" />
@@ -67,6 +69,10 @@
<Content Include="DynamicTexture.js"> <Content Include="DynamicTexture.js">
<DependentUpon>DynamicTexture.ts</DependentUpon> <DependentUpon>DynamicTexture.ts</DependentUpon>
</Content> </Content>
<TypeScriptCompile Include="FXManager.ts" />
<Content Include="FXManager.js">
<DependentUpon>FXManager.ts</DependentUpon>
</Content>
<Content Include="Game.js"> <Content Include="Game.js">
<DependentUpon>Game.ts</DependentUpon> <DependentUpon>Game.ts</DependentUpon>
</Content> </Content>
@@ -85,6 +91,14 @@
<Content Include="gameobjects\Particle.js"> <Content Include="gameobjects\Particle.js">
<DependentUpon>Particle.ts</DependentUpon> <DependentUpon>Particle.ts</DependentUpon>
</Content> </Content>
<TypeScriptCompile Include="gameobjects\ScrollZone.ts" />
<TypeScriptCompile Include="gameobjects\ScrollRegion.ts" />
<Content Include="gameobjects\ScrollRegion.js">
<DependentUpon>ScrollRegion.ts</DependentUpon>
</Content>
<Content Include="gameobjects\ScrollZone.js">
<DependentUpon>ScrollZone.ts</DependentUpon>
</Content>
<Content Include="gameobjects\Sprite.js"> <Content Include="gameobjects\Sprite.js">
<DependentUpon>Sprite.ts</DependentUpon> <DependentUpon>Sprite.ts</DependentUpon>
</Content> </Content>
@@ -107,12 +121,24 @@
<Content Include="geom\Point.js"> <Content Include="geom\Point.js">
<DependentUpon>Point.ts</DependentUpon> <DependentUpon>Point.ts</DependentUpon>
</Content> </Content>
<TypeScriptCompile Include="geom\Quad.ts" />
<Content Include="geom\Quad.js">
<DependentUpon>Quad.ts</DependentUpon>
</Content>
<Content Include="geom\Rectangle.js"> <Content Include="geom\Rectangle.js">
<DependentUpon>Rectangle.ts</DependentUpon> <DependentUpon>Rectangle.ts</DependentUpon>
</Content> </Content>
<Content Include="SoundManager.js"> <Content Include="SoundManager.js">
<DependentUpon>SoundManager.ts</DependentUpon> <DependentUpon>SoundManager.ts</DependentUpon>
</Content> </Content>
<TypeScriptCompile Include="system\screens\PauseScreen.ts" />
<TypeScriptCompile Include="system\screens\BootScreen.ts" />
<Content Include="system\screens\BootScreen.js">
<DependentUpon>BootScreen.ts</DependentUpon>
</Content>
<Content Include="system\screens\PauseScreen.js">
<DependentUpon>PauseScreen.ts</DependentUpon>
</Content>
<Content Include="system\Sound.js"> <Content Include="system\Sound.js">
<DependentUpon>Sound.ts</DependentUpon> <DependentUpon>Sound.ts</DependentUpon>
</Content> </Content>
@@ -154,14 +180,14 @@
<Content Include="system\Tile.js"> <Content Include="system\Tile.js">
<DependentUpon>Tile.ts</DependentUpon> <DependentUpon>Tile.ts</DependentUpon>
</Content> </Content>
<Content Include="system\TilemapBuffer.js"> <TypeScriptCompile Include="system\TilemapLayer.ts" />
<DependentUpon>TilemapBuffer.ts</DependentUpon> <Content Include="system\TilemapLayer.js">
<DependentUpon>TilemapLayer.ts</DependentUpon>
</Content> </Content>
<Content Include="system\Tween.js"> <Content Include="system\Tween.js">
<DependentUpon>Tween.ts</DependentUpon> <DependentUpon>Tween.ts</DependentUpon>
</Content> </Content>
<TypeScriptCompile Include="system\Tween.ts" /> <TypeScriptCompile Include="system\Tween.ts" />
<TypeScriptCompile Include="system\TilemapBuffer.ts" />
<TypeScriptCompile Include="system\Tile.ts" /> <TypeScriptCompile Include="system\Tile.ts" />
<TypeScriptCompile Include="system\StageScaleMode.ts" /> <TypeScriptCompile Include="system\StageScaleMode.ts" />
<TypeScriptCompile Include="system\RequestAnimationFrame.ts" /> <TypeScriptCompile Include="system\RequestAnimationFrame.ts" />
+3
View File
@@ -0,0 +1,3 @@
module Phaser {
var VERSION: string;
}
+3 -3
View File
@@ -1,13 +1,13 @@
/** /**
* Phaser * Phaser
* *
* v0.9.1 - April 19th 2013 * v0.9.5 - April 28th 2013
* *
* A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi. * A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi.
* *
* Richard Davey (@photonstorm) * Richard Davey (@photonstorm)
* *
* Many thanks to Adam Saltsman (@ADAMATOMIC) for the original Flixel AS3 code on which Phaser is based. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel on which Phaser took a lot of inspiration.
* *
* "If you want your children to be intelligent, read them fairy tales." * "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales." * "If you want them to be more intelligent, read them more fairy tales."
@@ -16,6 +16,6 @@
module Phaser { module Phaser {
export var VERSION: string = 'Phaser version 0.9.1'; export var VERSION: string = 'Phaser version 0.9.5';
} }
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="SignalBinding.d.ts" />
module Phaser {
class Signal {
private _bindings;
private _prevParams;
static VERSION: string;
public memorize: bool;
private _shouldPropagate;
public active: bool;
public validateListener(listener, fnName): void;
private _registerListener(listener, isOnce, listenerContext, priority);
private _addBinding(binding);
private _indexOfListener(listener, context);
public has(listener, context?: any): bool;
public add(listener, listenerContext?: any, priority?: number): SignalBinding;
public addOnce(listener, listenerContext?: any, priority?: number): SignalBinding;
public remove(listener, context?: any);
public removeAll(): void;
public getNumListeners(): number;
public halt(): void;
public dispatch(...paramsArr: any[]): void;
public forget(): void;
public dispose(): void;
public toString(): string;
}
}
+10 -7
View File
@@ -211,7 +211,7 @@ module Phaser {
if (i !== -1) if (i !== -1)
{ {
this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal this._bindings[i]._destroy();
this._bindings.splice(i, 1); this._bindings.splice(i, 1);
} }
@@ -224,14 +224,17 @@ module Phaser {
*/ */
public removeAll() { public removeAll() {
var n: number = this._bindings.length; if (this._bindings)
while (n--)
{ {
this._bindings[n]._destroy(); var n: number = this._bindings.length;
}
this._bindings.length = 0; while (n--)
{
this._bindings[n]._destroy();
}
this._bindings.length = 0;
}
} }
+21
View File
@@ -0,0 +1,21 @@
/// <reference path="Signal.d.ts" />
module Phaser {
class SignalBinding {
constructor(signal: Signal, listener, isOnce: bool, listenerContext, priority?: number);
private _listener;
private _isOnce;
public context;
private _signal;
public priority: number;
public active: bool;
public params;
public execute(paramsArr?: any[]);
public detach();
public isBound(): bool;
public isOnce(): bool;
public getListener();
public getSignal(): Signal;
public _destroy(): void;
public toString(): string;
}
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="Game.d.ts" />
/// <reference path="system/Sound.d.ts" />
module Phaser {
class SoundManager {
constructor(game: Game);
private _game;
private _context;
private _gainNode;
private _volume;
public mute(): void;
public unmute(): void;
public volume : number;
public decode(key: string, callback?, sound?: Sound): void;
public play(key: string, volume?: number, loop?: bool): Sound;
}
}
+1 -1
View File
@@ -111,7 +111,7 @@ module Phaser {
var tempSound: Sound = new Sound(this._context, this._gainNode, null, volume, loop); var tempSound: Sound = new 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 is an async process, so we can return the Sound object anyway, it just won't be playing yet
this.decode(key, () => this.play(key), tempSound); this.decode(key, () => tempSound.play(), tempSound);
return tempSound; return tempSound;
} }
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="Phaser.d.ts" />
/// <reference path="Game.d.ts" />
/// <reference path="system/StageScaleMode.d.ts" />
/// <reference path="system/screens/BootScreen.d.ts" />
/// <reference path="system/screens/PauseScreen.d.ts" />
module Phaser {
class Stage {
constructor(game: Game, parent: string, width: number, height: number);
private _game;
private _bgColor;
private _bootScreen;
private _pauseScreen;
static ORIENTATION_LANDSCAPE: number;
static ORIENTATION_PORTRAIT: number;
public bounds: Rectangle;
public aspectRatio: number;
public clear: bool;
public canvas: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
public disablePauseScreen: bool;
public disableBootScreen: bool;
public offset: Point;
public scale: StageScaleMode;
public scaleMode: number;
public minScaleX: number;
public maxScaleX: number;
public minScaleY: number;
public maxScaleY: number;
public update(): void;
private visibilityChange(event);
private getOffset(element);
public strokeStyle: string;
public lineWidth: number;
public fillStyle: string;
public saveCanvasValues(): void;
public restoreCanvasValues(): void;
public backgroundColor : string;
public x : number;
public y : number;
public width : number;
public height : number;
public centerX : number;
public centerY : number;
public randomX : number;
public randomY : number;
}
}
+39 -70
View File
@@ -1,6 +1,8 @@
/// <reference path="Phaser.ts" /> /// <reference path="Phaser.ts" />
/// <reference path="Game.ts" /> /// <reference path="Game.ts" />
/// <reference path="system/StageScaleMode.ts" /> /// <reference path="system/StageScaleMode.ts" />
/// <reference path="system/screens/BootScreen.ts" />
/// <reference path="system/screens/PauseScreen.ts" />
/** /**
* Phaser - Stage * Phaser - Stage
@@ -43,8 +45,11 @@ module Phaser {
this.scaleMode = StageScaleMode.NO_SCALE; this.scaleMode = StageScaleMode.NO_SCALE;
this.scale = new StageScaleMode(this._game); this.scale = new StageScaleMode(this._game);
//document.addEventListener('visibilitychange', (event) => this.visibilityChange(event), false); this._bootScreen = new BootScreen(this._game);
//document.addEventListener('webkitvisibilitychange', (event) => this.visibilityChange(event), false); this._pauseScreen = new PauseScreen(this._game, width, height);
document.addEventListener('visibilitychange', (event) => this.visibilityChange(event), false);
document.addEventListener('webkitvisibilitychange', (event) => this.visibilityChange(event), false);
window.onblur = (event) => this.visibilityChange(event); window.onblur = (event) => this.visibilityChange(event);
window.onfocus = (event) => this.visibilityChange(event); window.onfocus = (event) => this.visibilityChange(event);
@@ -52,7 +57,8 @@ module Phaser {
private _game: Game; private _game: Game;
private _bgColor: string; private _bgColor: string;
private _bootScreen;
private _pauseScreen;
public static ORIENTATION_LANDSCAPE: number = 0; public static ORIENTATION_LANDSCAPE: number = 0;
public static ORIENTATION_PORTRAIT: number = 1; public static ORIENTATION_PORTRAIT: number = 1;
@@ -62,6 +68,8 @@ module Phaser {
public clear: bool = true; public clear: bool = true;
public canvas: HTMLCanvasElement; public canvas: HTMLCanvasElement;
public context: CanvasRenderingContext2D; public context: CanvasRenderingContext2D;
public disablePauseScreen: bool = false;
public disableBootScreen: bool = false;
public offset: Point; public offset: Point;
public scale: StageScaleMode; public scale: StageScaleMode;
public scaleMode: number; public scaleMode: number;
@@ -81,83 +89,46 @@ module Phaser {
this.context.clearRect(0, 0, this.width, this.height); this.context.clearRect(0, 0, this.width, this.height);
} }
} if (this._game.isRunning == false && this.disableBootScreen == false)
{
this._bootScreen.update();
this._bootScreen.render();
}
public renderDebugInfo() { if (this._game.paused == true && this.disablePauseScreen == false)
{
this.context.fillStyle = 'rgb(255,255,255)'; this._pauseScreen.update();
this.context.fillText(Phaser.VERSION, 10, 20); this._pauseScreen.render();
this.context.fillText('Game Size: ' + this.width + ' x ' + this.height, 10, 40); }
this.context.fillText('x: ' + this.x + ' y: ' + this.y, 10, 60);
} }
private visibilityChange(event) { private visibilityChange(event) {
if (event.type == 'blur' && this._game.paused == false && this._game.isBooted == true) if (this.disablePauseScreen)
{ {
this._game.paused = true; return;
this.drawPauseScreen(); }
if (event.type === 'blur' || document['hidden'] === true || document['webkitHidden'] === true)
{
if (this._game.paused == false)
{
this._pauseScreen.onPaused();
this.saveCanvasValues();
this._game.paused = true;
}
} }
else if (event.type == 'focus') else if (event.type == 'focus')
{ {
this._game.paused = false; if (this._game.paused == true)
{
this._pauseScreen.onResume();
this._game.paused = false;
this.restoreCanvasValues();
}
} }
//if (document['hidden'] === true || document['webkitHidden'] === true)
}
public drawInitScreen() {
this.context.fillStyle = 'rgb(40, 40, 40)';
this.context.fillRect(0, 0, this.width, this.height);
this.context.fillStyle = 'rgb(255,255,255)';
this.context.font = 'bold 18px Arial';
this.context.textBaseline = 'top';
this.context.fillText(Phaser.VERSION, 54, 32);
this.context.fillText('Game Size: ' + this.width + ' x ' + this.height, 32, 64);
this.context.fillText('www.photonstorm.com', 32, 96);
this.context.font = '16px Arial';
this.context.fillText('You are seeing this screen because you didn\'t specify any default', 32, 160);
this.context.fillText('functions in the Game constructor, or use Game.loadState()', 32, 184);
var image = new Image();
var that = this;
image.onload = function () {
that.context.drawImage(image, 32, 32);
};
image.src = this._logo;
}
private drawPauseScreen() {
this.saveCanvasValues();
this.context.fillStyle = 'rgba(0, 0, 0, 0.4)';
this.context.fillRect(0, 0, this.width, this.height);
// Draw a 'play' arrow
var arrowWidth = Math.round(this.width / 2);
var arrowHeight = Math.round(this.height / 2);
var sx = this.centerX - arrowWidth / 2;
var sy = this.centerY - arrowHeight / 2;
this.context.beginPath();
this.context.moveTo(sx, sy);
this.context.lineTo(sx, sy + arrowHeight);
this.context.lineTo(sx + arrowWidth, this.centerY);
this.context.fillStyle = 'rgba(255, 255, 255, 0.8)';
this.context.fill();
this.context.closePath();
this.restoreCanvasValues();
} }
private getOffset(element): Point { private getOffset(element): Point {
@@ -233,8 +204,6 @@ module Phaser {
return Math.round(Math.random() * this.bounds.height); return Math.round(Math.random() * this.bounds.height);
} }
private _logo: string = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAO1JREFUeNpi/P//PwM6YGRkxBQEAqBaRnQxFmwa10d6MAjrMqMofHv5L1we2SBGmAtAktg0ogOQQYHLd8ANYYFpPtTmzUAMAFmwnsEDrAdkCAvMZlIAsiFMMAEYsKvaSrQhIMCELkGsV2AAbIC8gCQYgwKIUABiNYBf9yoYH7n7n6CzN274g2IYEyFbsNmKLIaSkHpP7WSwUfbA0ASzFQRslBlxp0RcAF0TRhggA3zhAJIDpUKU5A9KyshpHDkjFZu5g2nJMFcwXVJSgqIGnBKx5bKenh4w/XzVbgbPtlIUcVgSxuoCUgHIIIAAAwArtXwJBABO6QAAAABJRU5ErkJggg==";
} }
} }
+8 -4
View File
@@ -66,8 +66,8 @@ module Phaser {
return this.game.world.createSprite(x, y, key); return this.game.world.createSprite(x, y, key);
} }
public createDynamicTexture(key: string, width: number, height: number): DynamicTexture { public createDynamicTexture(width: number, height: number): DynamicTexture {
return this.game.world.createDynamicTexture(key, width, height); return this.game.world.createDynamicTexture(width, height);
} }
public createGroup(MaxSize?: number = 0): Group { public createGroup(MaxSize?: number = 0): Group {
@@ -82,8 +82,12 @@ module Phaser {
return this.game.world.createEmitter(x, y, size); return this.game.world.createEmitter(x, y, size);
} }
public createTilemap(key: string, mapData: string, format: number, tileWidth?: number, tileHeight?: number): Tilemap { public createScrollZone(key: string, x?: number = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone {
return this.game.world.createTilemap(key, mapData, format, tileWidth, tileHeight); return this.game.world.createScrollZone(key, x, y, width, height);
}
public createTilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap {
return this.game.world.createTilemap(key, mapData, format, resizeWorld, tileWidth, tileHeight);
} }
public createTween(obj): Tween { public createTween(obj): Tween {
+25
View File
@@ -0,0 +1,25 @@
/// <reference path="Game.d.ts" />
module Phaser {
class Time {
constructor(game: Game);
private _game;
private _started;
public timeScale: number;
public elapsed: number;
public time: number;
public now: number;
public delta: number;
public totalElapsedSeconds : number;
public fps: number;
public fpsMin: number;
public fpsMax: number;
public msMin: number;
public msMax: number;
public frames: number;
private _timeLastSecond;
public update(): void;
public elapsedSince(since: number): number;
public elapsedSecondsSince(since: number): number;
public reset(): void;
}
}
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="Game.d.ts" />
/// <reference path="system/Tween.d.ts" />
module Phaser {
class TweenManager {
constructor(game: Game);
private _game;
private _tweens;
public getAll(): Tween[];
public removeAll(): void;
public create(object): Tween;
public add(tween: Tween): Tween;
public remove(tween: Tween): void;
public update(): bool;
}
}
+32
View File
@@ -0,0 +1,32 @@
/// <reference path="Game.d.ts" />
module Phaser {
class World {
constructor(game: Game, width: number, height: number);
private _game;
public cameras: CameraManager;
public group: Group;
public bounds: Rectangle;
public worldDivisions: number;
public update(): void;
public render(): void;
public destroy(): void;
public setSize(width: number, height: number, updateCameraBounds?: bool): void;
public width : number;
public height : number;
public centerX : number;
public centerY : number;
public randomX : number;
public randomY : number;
public createCamera(x: number, y: number, width: number, height: number): Camera;
public removeCamera(id: number): bool;
public getAllCameras(): Camera[];
public createSprite(x: number, y: number, key?: string): Sprite;
public createGeomSprite(x: number, y: number): GeomSprite;
public createDynamicTexture(width: number, height: number): DynamicTexture;
public createGroup(MaxSize?: number): Group;
public createScrollZone(key: string, x?: number, y?: number, width?: number, height?: number): ScrollZone;
public createTilemap(key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number): Tilemap;
public createParticle(): Particle;
public createEmitter(x?: number, y?: number, size?: number): Emitter;
}
}
+17 -27
View File
@@ -16,9 +16,9 @@ module Phaser {
this._game = game; this._game = game;
this._cameras = new CameraManager(this._game, 0, 0, width, height); this.cameras = new CameraManager(this._game, 0, 0, width, height);
this._game.camera = this._cameras.current; this._game.camera = this.cameras.current;
this.group = new Group(this._game, 0); this.group = new Group(this._game, 0);
@@ -29,8 +29,8 @@ module Phaser {
} }
private _game: Game; private _game: Game;
private _cameras: CameraManager;
public cameras: CameraManager;
public group: Group; public group: Group;
public bounds: Rectangle; public bounds: Rectangle;
public worldDivisions: number; public worldDivisions: number;
@@ -41,14 +41,14 @@ module Phaser {
this.group.update(); this.group.update();
this.group.postUpdate(); this.group.postUpdate();
this._cameras.update(); this.cameras.update();
} }
public render() { public render() {
// Unlike in flixel our render process is camera driven, not group driven // Unlike in flixel our render process is camera driven, not group driven
this._cameras.render(); this.cameras.render();
} }
@@ -56,7 +56,7 @@ module Phaser {
this.group.destroy(); this.group.destroy();
this._cameras.destroy(); this.cameras.destroy();
} }
@@ -108,29 +108,19 @@ module Phaser {
// Cameras // Cameras
public addExistingCamera(cam: Camera): Camera {
//return this._cameras.addCamera(x, y, width, height);
return cam;
}
public createCamera(x: number, y: number, width: number, height: number): Camera { public createCamera(x: number, y: number, width: number, height: number): Camera {
return this._cameras.addCamera(x, y, width, height); return this.cameras.addCamera(x, y, width, height);
} }
public removeCamera(id: number): bool { public removeCamera(id: number): bool {
return this._cameras.removeCamera(id); return this.cameras.removeCamera(id);
} }
public getAllCameras(): Camera[] { public getAllCameras(): Camera[] {
return this._cameras.getAll(); return this.cameras.getAll();
} }
// Sprites // Game Objects
// Drop this?
public addExistingSprite(sprite: Sprite): Sprite {
return <Sprite> this.group.add(sprite);
}
public createSprite(x: number, y: number, key?: string = ''): Sprite { public createSprite(x: number, y: number, key?: string = ''): Sprite {
return <Sprite> this.group.add(new Sprite(this._game, x, y, key)); return <Sprite> this.group.add(new Sprite(this._game, x, y, key));
@@ -140,21 +130,21 @@ module Phaser {
return <GeomSprite> this.group.add(new GeomSprite(this._game, x, y)); return <GeomSprite> this.group.add(new GeomSprite(this._game, x, y));
} }
public createDynamicTexture(key: string, width: number, height: number): DynamicTexture { public createDynamicTexture(width: number, height: number): DynamicTexture {
return new DynamicTexture(this._game, key, width, height); return new DynamicTexture(this._game, width, height);
} }
public createGroup(MaxSize?: number = 0): Group { public createGroup(MaxSize?: number = 0): Group {
return <Group> this.group.add(new Group(this._game, MaxSize)); return <Group> this.group.add(new Group(this._game, MaxSize));
} }
// Tilemaps public createScrollZone(key: string, x?: number = 0, y?: number = 0, width?: number = 0, height?: number = 0): ScrollZone {
return <ScrollZone> this.group.add(new ScrollZone(this._game, key, x, y, width, height));
public createTilemap(key: string, mapData: string, format: number, tileWidth?: number, tileHeight?: number): Tilemap {
return <Tilemap> this.group.add(new Tilemap(this._game, key, mapData, format, tileWidth, tileHeight));
} }
// Emitters public createTilemap(key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0): Tilemap {
return <Tilemap> this.group.add(new Tilemap(this._game, key, mapData, format, resizeWorld, tileWidth, tileHeight));
}
public createParticle(): Particle { public createParticle(): Particle {
return new Particle(this._game); return new Particle(this._game);
+38
View File
@@ -0,0 +1,38 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../Group.d.ts" />
module Phaser {
class Emitter extends Group {
constructor(game: Game, X?: number, Y?: number, Size?: number);
public x: number;
public y: number;
public width: number;
public height: number;
public minParticleSpeed: MicroPoint;
public maxParticleSpeed: MicroPoint;
public particleDrag: MicroPoint;
public minRotation: number;
public maxRotation: number;
public gravity: number;
public on: bool;
public frequency: number;
public lifespan: number;
public bounce: number;
public particleClass;
private _quantity;
private _explode;
private _timer;
private _counter;
private _point;
public destroy(): void;
public makeParticles(Graphics, Quantity?: number, BakedRotations?: number, Multiple?: bool, Collide?: number): Emitter;
public update(): void;
public kill(): void;
public start(Explode?: bool, Lifespan?: number, Frequency?: number, Quantity?: number): void;
public emitParticle(): void;
public setSize(Width: number, Height: number): void;
public setXSpeed(Min?: number, Max?: number): void;
public setYSpeed(Min?: number, Max?: number): void;
public setRotation(Min?: number, Max?: number): void;
public at(Object): void;
}
}
+11 -10
View File
@@ -27,13 +27,13 @@ module Phaser {
this.y = Y; this.y = Y;
this.width = 0; this.width = 0;
this.height = 0; this.height = 0;
this.minParticleSpeed = new Point(-100, -100); this.minParticleSpeed = new MicroPoint(-100, -100);
this.maxParticleSpeed = new Point(100, 100); this.maxParticleSpeed = new MicroPoint(100, 100);
this.minRotation = -360; this.minRotation = -360;
this.maxRotation = 360; this.maxRotation = 360;
this.gravity = 0; this.gravity = 0;
this.particleClass = null; this.particleClass = null;
this.particleDrag = new Point(); this.particleDrag = new MicroPoint();
this.frequency = 0.1; this.frequency = 0.1;
this.lifespan = 3; this.lifespan = 3;
this.bounce = 0; this.bounce = 0;
@@ -41,7 +41,7 @@ module Phaser {
this._counter = 0; this._counter = 0;
this._explode = true; this._explode = true;
this.on = false; this.on = false;
this._point = new Point(); this._point = new MicroPoint();
} }
/** /**
@@ -68,18 +68,18 @@ module Phaser {
* The minimum possible velocity of a particle. * The minimum possible velocity of a particle.
* The default value is (-100,-100). * The default value is (-100,-100).
*/ */
public minParticleSpeed: Point; public minParticleSpeed: MicroPoint;
/** /**
* The maximum possible velocity of a particle. * The maximum possible velocity of a particle.
* The default value is (100,100). * The default value is (100,100).
*/ */
public maxParticleSpeed: Point; public maxParticleSpeed: MicroPoint;
/** /**
* The X and Y drag component of particles launched from the emitter. * The X and Y drag component of particles launched from the emitter.
*/ */
public particleDrag: Point; public particleDrag: MicroPoint;
/** /**
* The minimum possible angular velocity of a particle. The default value is -360. * The minimum possible angular velocity of a particle. The default value is -360.
@@ -149,7 +149,7 @@ module Phaser {
/** /**
* Internal point object, handy for reusing for memory mgmt purposes. * Internal point object, handy for reusing for memory mgmt purposes.
*/ */
private _point: Point; private _point: MicroPoint;
/** /**
* Clean up memory. * Clean up memory.
@@ -174,7 +174,7 @@ module Phaser {
* *
* @return This Emitter instance (nice for chaining stuff together, if you're into that). * @return This Emitter instance (nice for chaining stuff together, if you're into that).
*/ */
public makeParticles(Graphics, Quantity: number = 50, BakedRotations: number = 16, Multiple: bool = false, Collide: number = 0.8): Emitter { public makeParticles(Graphics, Quantity: number = 50, BakedRotations: number = 16, Multiple: bool = false, Collide: number = 0): Emitter {
this.maxSize = Quantity; this.maxSize = Quantity;
@@ -236,6 +236,7 @@ module Phaser {
if (Collide > 0) if (Collide > 0)
{ {
particle.allowCollisions = Collision.ANY;
particle.width *= Collide; particle.width *= Collide;
particle.height *= Collide; particle.height *= Collide;
//particle.centerOffsets(); //particle.centerOffsets();
@@ -372,7 +373,7 @@ module Phaser {
particle.acceleration.y = this.gravity; particle.acceleration.y = this.gravity;
if (this.minRotation != this.maxRotation) if (this.minRotation != this.maxRotation && this.minRotation !== 0 && this.maxRotation !== 0)
{ {
particle.angularVelocity = this.minRotation + this._game.math.random() * (this.maxRotation - this.minRotation); particle.angularVelocity = this.minRotation + this._game.math.random() * (this.maxRotation - this.minRotation);
} }
+84
View File
@@ -0,0 +1,84 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../Basic.d.ts" />
/// <reference path="../Signal.d.ts" />
module Phaser {
class GameObject extends Basic {
constructor(game: Game, x?: number, y?: number, width?: number, height?: number);
private _angle;
static ALIGN_TOP_LEFT: number;
static ALIGN_TOP_CENTER: number;
static ALIGN_TOP_RIGHT: number;
static ALIGN_CENTER_LEFT: number;
static ALIGN_CENTER: number;
static ALIGN_CENTER_RIGHT: number;
static ALIGN_BOTTOM_LEFT: number;
static ALIGN_BOTTOM_CENTER: number;
static ALIGN_BOTTOM_RIGHT: number;
static OUT_OF_BOUNDS_STOP: number;
static OUT_OF_BOUNDS_KILL: number;
public _point: MicroPoint;
public cameraBlacklist: number[];
public bounds: Rectangle;
public worldBounds: Quad;
public outOfBoundsAction: number;
public align: number;
public facing: number;
public alpha: number;
public scale: MicroPoint;
public origin: MicroPoint;
public z: number;
public rotationOffset: number;
public renderRotation: bool;
public immovable: bool;
public velocity: MicroPoint;
public mass: number;
public elasticity: number;
public acceleration: MicroPoint;
public drag: MicroPoint;
public maxVelocity: MicroPoint;
public angularVelocity: number;
public angularAcceleration: number;
public angularDrag: number;
public maxAngular: number;
public scrollFactor: MicroPoint;
public health: number;
public moves: bool;
public touching: number;
public wasTouching: number;
public allowCollisions: number;
public last: MicroPoint;
public inputEnabled: bool;
private _inputOver;
public onInputOver: Signal;
public onInputOut: Signal;
public onInputDown: Signal;
public onInputUp: Signal;
public preUpdate(): void;
public update(): void;
public postUpdate(): void;
private updateInput();
private updateMotion();
public overlaps(ObjectOrGroup, InScreenSpace?: bool, Camera?: Camera): bool;
public overlapsAt(X: number, Y: number, ObjectOrGroup, InScreenSpace?: bool, Camera?: Camera): bool;
public overlapsPoint(point: Point, InScreenSpace?: bool, Camera?: Camera): bool;
public onScreen(Camera?: Camera): bool;
public getScreenXY(point?: MicroPoint, Camera?: Camera): MicroPoint;
public solid : bool;
public getMidpoint(point?: MicroPoint): MicroPoint;
public reset(X: number, Y: number): void;
public isTouching(Direction: number): bool;
public justTouched(Direction: number): bool;
public hurt(Damage: number): void;
public setBounds(x: number, y: number, width: number, height: number): void;
public hideFromCamera(camera: Camera): void;
public showToCamera(camera: Camera): void;
public clearCameraList(): void;
public destroy(): void;
public x : number;
public y : number;
public rotation : number;
public angle : number;
public width : number;
public height : number;
}
}
+97 -30
View File
@@ -29,11 +29,12 @@ module Phaser {
this.last = new MicroPoint(x, y); this.last = new MicroPoint(x, y);
this.origin = new MicroPoint(this.bounds.halfWidth, this.bounds.halfHeight); this.origin = new MicroPoint(this.bounds.halfWidth, this.bounds.halfHeight);
this.align = GameObject.ALIGN_TOP_LEFT; this.align = GameObject.ALIGN_TOP_LEFT;
this.mass = 1.0; this.mass = 1;
this.elasticity = 0.0; this.elasticity = 0;
this.health = 1; this.health = 1;
this.immovable = false; this.immovable = false;
this.moves = true; this.moves = true;
this.worldBounds = null;
this.touching = Collision.NONE; this.touching = Collision.NONE;
this.wasTouching = Collision.NONE; this.wasTouching = Collision.NONE;
@@ -50,7 +51,8 @@ module Phaser {
this.angularDrag = 0; this.angularDrag = 0;
this.maxAngular = 10000; this.maxAngular = 10000;
this.scrollFactor = new MicroPoint(1.0, 1.0); this.cameraBlacklist = [];
this.scrollFactor = new MicroPoint(1, 1);
} }
@@ -66,9 +68,15 @@ module Phaser {
public static ALIGN_BOTTOM_CENTER: number = 7; public static ALIGN_BOTTOM_CENTER: number = 7;
public static ALIGN_BOTTOM_RIGHT: number = 8; public static ALIGN_BOTTOM_RIGHT: number = 8;
public static OUT_OF_BOUNDS_STOP: number = 0;
public static OUT_OF_BOUNDS_KILL: number = 1;
public _point: MicroPoint; public _point: MicroPoint;
public cameraBlacklist: number[];
public bounds: Rectangle; public bounds: Rectangle;
public worldBounds: Quad;
public outOfBoundsAction: number = 0;
public align: number; public align: number;
public facing: number; public facing: number;
public alpha: number; public alpha: number;
@@ -76,6 +84,13 @@ module Phaser {
public origin: MicroPoint; public origin: MicroPoint;
public z: number = 0; public z: number = 0;
// This value is added to the angle of the GameObject.
// For example if you had a sprite drawn facing straight up then you could set
// rotationOffset to 90 and it would correspond correctly with Phasers rotation system
public rotationOffset: number = 0;
public renderRotation: bool = true;
// Physics properties // Physics properties
public immovable: bool; public immovable: bool;
@@ -131,6 +146,37 @@ module Phaser {
this.updateMotion(); this.updateMotion();
} }
if (this.worldBounds != null)
{
if (this.outOfBoundsAction == GameObject.OUT_OF_BOUNDS_KILL)
{
if (this.x < this.worldBounds.x || this.x > this.worldBounds.right || this.y < this.worldBounds.y || this.y > this.worldBounds.bottom)
{
this.kill();
}
}
else
{
if (this.x < this.worldBounds.x)
{
this.x = this.worldBounds.x;
}
else if (this.x > this.worldBounds.right)
{
this.x = this.worldBounds.right;
}
if (this.y < this.worldBounds.y)
{
this.y = this.worldBounds.y;
}
else if (this.y > this.worldBounds.bottom)
{
this.y = this.worldBounds.bottom;
}
}
}
if (this.inputEnabled) if (this.inputEnabled)
{ {
this.updateInput(); this.updateInput();
@@ -170,7 +216,7 @@ module Phaser {
/** /**
* Checks to see if some <code>GameObject</code> overlaps this <code>GameObject</code> or <code>Group</code>. * Checks to see if some <code>GameObject</code> overlaps this <code>GameObject</code> or <code>Group</code>.
* If the group has a LOT of things in it, it might be faster to use <code>G.overlaps()</code>. * If the group has a LOT of things in it, it might be faster to use <code>Collision.overlaps()</code>.
* WARNING: Currently tilemaps do NOT support screen space overlap checks! * WARNING: Currently tilemaps do NOT support screen space overlap checks!
* *
* @param ObjectOrGroup The object or group being tested. * @param ObjectOrGroup The object or group being tested.
@@ -199,17 +245,6 @@ module Phaser {
} }
/*
if (typeof ObjectOrGroup === 'Tilemap')
{
//Since tilemap's have to be the caller, not the target, to do proper tile-based collisions,
// we redirect the call to the tilemap overlap here.
return ObjectOrGroup.overlaps(this, InScreenSpace, Camera);
}
*/
//var object: GameObject = ObjectOrGroup;
if (!InScreenSpace) if (!InScreenSpace)
{ {
return (ObjectOrGroup.x + ObjectOrGroup.width > this.x) && (ObjectOrGroup.x < this.x + this.width) && return (ObjectOrGroup.x + ObjectOrGroup.width > this.x) && (ObjectOrGroup.x < this.x + this.width) &&
@@ -262,20 +297,6 @@ module Phaser {
return results; return results;
} }
/*
if (typeof ObjectOrGroup === 'Tilemap')
{
//Since tilemap's have to be the caller, not the target, to do proper tile-based collisions,
// we redirect the call to the tilemap overlap here.
//However, since this is overlapsAt(), we also have to invent the appropriate position for the tilemap.
//So we calculate the offset between the player and the requested position, and subtract that from the tilemap.
var tilemap: Tilemap = ObjectOrGroup;
return tilemap.overlapsAt(tilemap.x - (X - this.x), tilemap.y - (Y - this.y), this, InScreenSpace, Camera);
}
*/
//var object: GameObject = ObjectOrGroup;
if (!InScreenSpace) if (!InScreenSpace)
{ {
return (ObjectOrGroup.x + ObjectOrGroup.width > X) && (ObjectOrGroup.x < X + this.width) && return (ObjectOrGroup.x + ObjectOrGroup.width > X) && (ObjectOrGroup.x < X + this.width) &&
@@ -302,7 +323,7 @@ module Phaser {
* Checks to see if a point in 2D world space overlaps this <code>GameObject</code>. * Checks to see if a point in 2D world space overlaps this <code>GameObject</code>.
* *
* @param Point The point in world space you want to check. * @param Point The point in world space you want to check.
* @param InScreenSpace Whether to take scroll factors numbero account when checking for overlap. * @param InScreenSpace Whether to take scroll factors into account when checking for overlap.
* @param Camera Specify which game camera you want. If null getScreenXY() will just grab the first global camera. * @param 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. * @return Whether or not the point overlaps this object.
@@ -484,6 +505,44 @@ module Phaser {
} }
/**
* 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.
*/
public setBounds(x: number, y: number, width: number, height: number) {
this.worldBounds = new Quad(x, y, width, height);
}
/**
* If you do not wish this object to be visible to a specific camera, pass the camera here.
*/
public hideFromCamera(camera: Camera) {
if (this.cameraBlacklist.indexOf(camera.ID) == -1)
{
this.cameraBlacklist.push(camera.ID);
}
}
public showToCamera(camera: Camera) {
if (this.cameraBlacklist.indexOf(camera.ID) !== -1)
{
this.cameraBlacklist.slice(this.cameraBlacklist.indexOf(camera.ID), 1);
}
}
public clearCameraList() {
this.cameraBlacklist.length = 0;
}
public destroy() { public destroy() {
} }
@@ -520,6 +579,14 @@ module Phaser {
this._angle = this._game.math.wrap(value, 360, 0); this._angle = this._game.math.wrap(value, 360, 0);
} }
public set width(value:number) {
this.bounds.width = value;
}
public set height(value:number) {
this.bounds.height = value;
}
public get width(): number { public get width(): number {
return this.bounds.width; return this.bounds.width;
} }
+40
View File
@@ -0,0 +1,40 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class GeomSprite extends GameObject {
constructor(game: Game, x?: number, y?: number);
private _dx;
private _dy;
private _dw;
private _dh;
public type: number;
static UNASSIGNED: number;
static CIRCLE: number;
static LINE: number;
static POINT: number;
static RECTANGLE: number;
public circle: Circle;
public line: Line;
public point: Point;
public rect: Rectangle;
public renderOutline: bool;
public renderFill: bool;
public lineWidth: number;
public lineColor: string;
public fillColor: string;
public loadCircle(circle: Circle): GeomSprite;
public loadLine(line: Line): GeomSprite;
public loadPoint(point: Point): GeomSprite;
public loadRectangle(rect: Rectangle): GeomSprite;
public createCircle(diameter: number): GeomSprite;
public createLine(x: number, y: number): GeomSprite;
public createPoint(): GeomSprite;
public createRectangle(width: number, height: number): GeomSprite;
public refresh(): void;
public update(): void;
public inCamera(camera: Rectangle): bool;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool;
public renderPoint(offsetX, offsetY, point, size): void;
public renderDebugInfo(x: number, y: number, color?: string): void;
public collide(source: GeomSprite): bool;
}
}
+21 -14
View File
@@ -190,7 +190,7 @@ module Phaser {
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool { public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool {
// Render checks // Render checks
if (this.type == GeomSprite.UNASSIGNED || this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.inCamera(camera.worldView) == false) if (this.type == GeomSprite.UNASSIGNED || this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false)
{ {
return false; return false;
} }
@@ -301,15 +301,24 @@ module Phaser {
// And now the edge points // And now the edge points
this._game.stage.context.fillStyle = 'rgb(255,255,255)'; this._game.stage.context.fillStyle = 'rgb(255,255,255)';
this.renderPoint(this._dx, this._dy, this.rect.topLeft, 2); //this.renderPoint(this.rect.topLeft, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.topCenter, 2); //this.renderPoint(this.rect.topCenter, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.topRight, 2); //this.renderPoint(this.rect.topRight, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.leftCenter, 2); //this.renderPoint(this.rect.leftCenter, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.center, 2); //this.renderPoint(this.rect.center, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.rightCenter, 2); //this.renderPoint(this.rect.rightCenter, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomLeft, 2); //this.renderPoint(this.rect.bottomLeft, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomCenter, 2); //this.renderPoint(this.rect.bottomCenter, this._dx, this._dy, 2);
this.renderPoint(this._dx, this._dy, this.rect.bottomRight, 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);
} }
@@ -330,11 +339,9 @@ module Phaser {
} }
public renderPoint(offsetX, offsetY, point, size) { public renderPoint(point, offsetX?: number = 0, offsetY?: number = 0, size?: number = 1) {
offsetX = 0; this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, size, size);
offsetY = 0;
this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, 1, 1);
} }
+11
View File
@@ -0,0 +1,11 @@
/// <reference path="../Game.d.ts" />
/// <reference path="Sprite.d.ts" />
module Phaser {
class Particle extends Sprite {
constructor(game: Game);
public lifespan: number;
public friction: number;
public update(): void;
public onEmit(): void;
}
}
+2
View File
@@ -22,6 +22,7 @@ module Phaser {
this.lifespan = 0; this.lifespan = 0;
this.friction = 500; this.friction = 500;
} }
/** /**
@@ -43,6 +44,7 @@ module Phaser {
* be dead yet, and then has some special bounce behavior if there is some gravity on it. * be dead yet, and then has some special bounce behavior if there is some gravity on it.
*/ */
public update() { public update() {
//lifespan behavior //lifespan behavior
if (this.lifespan <= 0) if (this.lifespan <= 0)
{ {
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../geom/Quad.d.ts" />
module Phaser {
class ScrollRegion {
constructor(x: number, y: number, width: number, height: number, speedX: number, speedY: number);
private _A;
private _B;
private _C;
private _D;
private _bounds;
private _scroll;
private _anchorWidth;
private _anchorHeight;
private _inverseWidth;
private _inverseHeight;
public visible: bool;
public scrollSpeed: MicroPoint;
public update(delta: number): void;
public render(context: CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number): void;
private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY);
}
}
+159
View File
@@ -0,0 +1,159 @@
/// <reference path="../Game.ts" />
/// <reference path="../geom/Quad.ts" />
/**
* Phaser - ScrollRegion
*
* Creates a scrolling region within a ScrollZone.
* It is scrolled via the scrollSpeed.x/y properties.
*/
module Phaser {
export class ScrollRegion{
constructor(x: number, y: number, width: number, height: number, speedX:number, speedY:number) {
// Our seamless scrolling quads
this._A = new Quad(x, y, width, height);
this._B = new Quad(x, y, width, height);
this._C = new Quad(x, y, width, height);
this._D = new Quad(x, y, width, height);
this._scroll = new MicroPoint();
this._bounds = new Quad(x, y, width, height);
this.scrollSpeed = new MicroPoint(speedX, speedY);
}
private _A: Quad;
private _B: Quad;
private _C: Quad;
private _D: Quad;
private _bounds: Quad;
private _scroll: MicroPoint;
private _anchorWidth: number = 0;
private _anchorHeight: number = 0;
private _inverseWidth: number = 0;
private _inverseHeight: number = 0;
public visible: bool = true;
public scrollSpeed: MicroPoint;
public update(delta: number) {
this._scroll.x += this.scrollSpeed.x;
this._scroll.y += this.scrollSpeed.y;
if (this._scroll.x > this._bounds.right)
{
this._scroll.x = this._bounds.x;
}
if (this._scroll.x < this._bounds.x)
{
this._scroll.x = this._bounds.right;
}
if (this._scroll.y > this._bounds.bottom)
{
this._scroll.y = this._bounds.y;
}
if (this._scroll.y < this._bounds.y)
{
this._scroll.y = this._bounds.bottom;
}
// Anchor Dimensions
this._anchorWidth = (this._bounds.width - this._scroll.x) + this._bounds.x;
this._anchorHeight = (this._bounds.height - this._scroll.y) + this._bounds.y;
if (this._anchorWidth > this._bounds.width)
{
this._anchorWidth = this._bounds.width;
}
if (this._anchorHeight > this._bounds.height)
{
this._anchorHeight = this._bounds.height;
}
this._inverseWidth = this._bounds.width - this._anchorWidth;
this._inverseHeight = this._bounds.height - this._anchorHeight;
// Quad A
this._A.setTo(this._scroll.x, this._scroll.y, this._anchorWidth, this._anchorHeight);
// Quad B
this._B.y = this._scroll.y;
this._B.width = this._inverseWidth;
this._B.height = this._anchorHeight;
// Quad C
this._C.x = this._scroll.x;
this._C.width = this._anchorWidth;
this._C.height = this._inverseHeight;
// Quad D
this._D.width = this._inverseWidth;
this._D.height = this._inverseHeight;
}
public render(context:CanvasRenderingContext2D, texture, dx: number, dy: number, dw: number, dh: number) {
if (this.visible == false)
{
return;
}
// dx/dy are the world coordinates to render the FULL ScrollZone into.
// This ScrollRegion may be smaller than that and offset from the dx/dy coordinates.
this.crop(context, texture, this._A.x, this._A.y, this._A.width, this._A.height, dx, dy, dw, dh, 0, 0);
this.crop(context, texture, this._B.x, this._B.y, this._B.width, this._B.height, dx, dy, dw, dh, this._A.width, 0);
this.crop(context, texture, this._C.x, this._C.y, this._C.width, this._C.height, dx, dy, dw, dh, 0, this._A.height);
this.crop(context, texture, this._D.x, this._D.y, this._D.width, this._D.height, dx, dy, dw, dh, this._C.width, this._A.height);
//context.fillStyle = 'rgb(255,255,255)';
//context.font = '18px Arial';
//context.fillText('QuadA: ' + this._A.toString(), 32, 450);
//context.fillText('QuadB: ' + this._B.toString(), 32, 480);
//context.fillText('QuadC: ' + this._C.toString(), 32, 510);
//context.fillText('QuadD: ' + this._D.toString(), 32, 540);
}
private crop(context, texture, srcX, srcY, srcW, srcH, destX, destY, destW, destH, offsetX, offsetY) {
offsetX += destX;
offsetY += destY;
if (srcW > (destX + destW) - offsetX)
{
srcW = (destX + destW) - offsetX;
}
if (srcH > (destY + destH) - offsetY)
{
srcH = (destY + destH) - offsetY;
}
srcX = Math.floor(srcX);
srcY = Math.floor(srcY);
srcW = Math.floor(srcW);
srcH = Math.floor(srcH);
offsetX = Math.floor(offsetX + this._bounds.x);
offsetY = Math.floor(offsetY + this._bounds.y);
if (srcW > 0 && srcH > 0)
{
context.drawImage(texture, srcX, srcY, srcW, srcH, offsetX, offsetY, srcW, srcH);
}
}
}
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../geom/Quad.d.ts" />
/// <reference path="ScrollRegion.d.ts" />
module Phaser {
class ScrollZone extends GameObject {
constructor(game: Game, key: string, x?: number, y?: number, width?: number, height?: number);
private _texture;
private _dynamicTexture;
private _dx;
private _dy;
private _dw;
private _dh;
public currentRegion: ScrollRegion;
public regions: ScrollRegion[];
public flipped: bool;
public addRegion(x: number, y: number, width: number, height: number, speedX?: number, speedY?: number): ScrollRegion;
public setSpeed(x: number, y: number): ScrollZone;
public update(): void;
public inCamera(camera: Rectangle): bool;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool;
private createRepeatingTexture(regionWidth, regionHeight);
}
}
+208
View File
@@ -0,0 +1,208 @@
/// <reference path="../Game.ts" />
/// <reference path="../geom/Quad.ts" />
/// <reference path="ScrollRegion.ts" />
/**
* Phaser - ScrollZone
*
* Creates a scrolling region of the given width and height from an image in the cache.
* The ScrollZone can be positioned anywhere in-world like a normal game object, re-act to physics, collision, etc.
* The image within it is scrolled via ScrollRegions and their scrollSpeed.x/y properties.
* If you create a scroll zone larger than the given source image it will create a DynamicTexture and fill it with a pattern of the source image.
*/
module Phaser {
export class ScrollZone extends GameObject {
constructor(game: Game, key:string, x: number = 0, y: number = 0, width?: number = 0, height?: number = 0) {
super(game, x, y, width, height);
this.regions = [];
if (this._game.cache.getImage(key))
{
this._texture = this._game.cache.getImage(key);
this.width = this._texture.width;
this.height = this._texture.height;
if (width > this._texture.width || height > this._texture.height)
{
// Create our repeating texture (as the source image wasn't large enough for the requested size)
this.createRepeatingTexture(width, height);
this.width = width;
this.height = height;
}
// Create a default ScrollRegion at the requested size
this.addRegion(0, 0, this.width, this.height);
// If the zone is smaller than the image itself then shrink the bounds
if ((width < this._texture.width || height < this._texture.height) && width !== 0 && height !== 0)
{
this.width = width;
this.height = height;
}
}
}
private _texture;
private _dynamicTexture: DynamicTexture = null;
// local rendering related temp vars to help avoid gc spikes
private _dx: number = 0;
private _dy: number = 0;
private _dw: number = 0;
private _dh: number = 0;
public currentRegion: ScrollRegion;
public regions: ScrollRegion[];
public flipped: bool = false;
public addRegion(x: number, y: number, width: number, height: number, speedX?:number = 0, speedY?:number = 0):ScrollRegion {
if (x > this.width || y > this.height || x < 0 || y < 0 || (x + width) > this.width || (y + height) > this.height)
{
throw Error('Invalid ScrollRegion defined. Cannot be larger than parent ScrollZone');
return;
}
this.currentRegion = new ScrollRegion(x, y, width, height, speedX, speedY);
this.regions.push(this.currentRegion);
return this.currentRegion;
}
public setSpeed(x: number, y: number) {
if (this.currentRegion)
{
this.currentRegion.scrollSpeed.setTo(x, y);
}
return this;
}
public update() {
for (var i = 0; i < this.regions.length; i++)
{
this.regions[i].update(this._game.time.delta);
}
}
public inCamera(camera: Rectangle): bool {
if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0)
{
this._dx = this.bounds.x - (camera.x * this.scrollFactor.x);
this._dy = this.bounds.y - (camera.y * this.scrollFactor.x);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.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.bounds, this.bounds.length);
}
}
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number) {
// Render checks
if (this.visible == false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false)
{
return false;
}
// Alpha
if (this.alpha !== 1)
{
var globalAlpha = this._game.stage.context.globalAlpha;
this._game.stage.context.globalAlpha = this.alpha;
}
this._dx = cameraOffsetX + (this.bounds.topLeft.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.topLeft.y - camera.worldView.y);
this._dw = this.bounds.width * this.scale.x;
this._dh = this.bounds.height * this.scale.y;
// Apply camera difference
if (this.scrollFactor.x !== 1.0 || this.scrollFactor.y !== 1.0)
{
this._dx -= (camera.worldView.x * this.scrollFactor.x);
this._dy -= (camera.worldView.y * this.scrollFactor.y);
}
// Rotation - needs to work from origin point really, but for now from center
if (this.angle !== 0 || this.flipped == true)
{
this._game.stage.context.save();
this._game.stage.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2));
if (this.angle !== 0)
{
this._game.stage.context.rotate(this.angle * (Math.PI / 180));
}
this._dx = -(this._dw / 2);
this._dy = -(this._dh / 2);
if (this.flipped == true)
{
this._game.stage.context.scale(-1, 1);
}
}
this._dx = Math.round(this._dx);
this._dy = Math.round(this._dy);
this._dw = Math.round(this._dw);
this._dh = Math.round(this._dh);
for (var i = 0; i < this.regions.length; i++)
{
if (this._dynamicTexture)
{
this.regions[i].render(this._game.stage.context, this._dynamicTexture.canvas, this._dx, this._dy, this._dw, this._dh);
}
else
{
this.regions[i].render(this._game.stage.context, this._texture, this._dx, this._dy, this._dw, this._dh);
}
}
if (globalAlpha > -1)
{
this._game.stage.context.globalAlpha = globalAlpha;
}
return true;
}
private createRepeatingTexture(regionWidth: number, regionHeight: number) {
// Work out how many we'll need of the source image to make it tile properly
var tileWidth = Math.ceil(this._texture.width / regionWidth) * regionWidth;
var tileHeight = Math.ceil(this._texture.height / regionHeight) * regionHeight;
this._dynamicTexture = new DynamicTexture(this._game, tileWidth, tileHeight);
this._dynamicTexture.context.rect(0, 0, tileWidth, tileHeight);
this._dynamicTexture.context.fillStyle = this._dynamicTexture.context.createPattern(this._texture, "repeat");
this._dynamicTexture.context.fill();
}
}
}
+34
View File
@@ -0,0 +1,34 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../AnimationManager.d.ts" />
/// <reference path="GameObject.d.ts" />
/// <reference path="../system/Camera.d.ts" />
module Phaser {
class Sprite extends GameObject {
constructor(game: Game, x?: number, y?: number, key?: string);
private _texture;
private _dynamicTexture;
private _sx;
private _sy;
private _sw;
private _sh;
private _dx;
private _dy;
private _dw;
private _dh;
public animations: AnimationManager;
public renderDebug: bool;
public renderDebugColor: string;
public renderDebugPointColor: string;
public flipped: bool;
public loadGraphic(key: string): Sprite;
public loadDynamicTexture(texture: DynamicTexture): Sprite;
public makeGraphic(width: number, height: number, color?: number): Sprite;
public inCamera(camera: Rectangle): bool;
public postUpdate(): void;
public frame : number;
public frameName : string;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool;
private renderBounds(camera, cameraOffsetX, cameraOffsetY);
public renderDebugInfo(x: number, y: number, color?: string): void;
}
}
+28 -21
View File
@@ -1,6 +1,7 @@
/// <reference path="../Game.ts" /> /// <reference path="../Game.ts" />
/// <reference path="../AnimationManager.ts" /> /// <reference path="../AnimationManager.ts" />
/// <reference path="GameObject.ts" /> /// <reference path="GameObject.ts" />
/// <reference path="../system/Camera.ts" />
/** /**
* Phaser - Sprite * Phaser - Sprite
@@ -51,6 +52,7 @@ module Phaser {
public renderDebug: bool = false; public renderDebug: bool = false;
public renderDebugColor: string = 'rgba(0,255,0,0.5)'; public renderDebugColor: string = 'rgba(0,255,0,0.5)';
public renderDebugPointColor: string = 'rgba(255,255,255,1)'; public renderDebugPointColor: string = 'rgba(255,255,255,1)';
public flipped: bool = false;
public loadGraphic(key: string): Sprite { public loadGraphic(key: string): Sprite {
@@ -125,7 +127,7 @@ module Phaser {
} }
public set frame(value?: number) { public set frame(value: number) {
this.animations.frame = value; this.animations.frame = value;
} }
@@ -133,7 +135,7 @@ module Phaser {
return this.animations.frame; return this.animations.frame;
} }
public set frameName(value?: string) { public set frameName(value: string) {
this.animations.frameName = value; this.animations.frameName = value;
} }
@@ -144,7 +146,7 @@ module Phaser {
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool { public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool {
// Render checks // Render checks
if (this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.inCamera(camera.worldView) == false) if (this.visible == false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1 || this.cameraBlacklist.indexOf(camera.ID) !== -1 || this.inCamera(camera.worldView) == false)
{ {
return false; return false;
} }
@@ -156,13 +158,6 @@ module Phaser {
this._game.stage.context.globalAlpha = this.alpha; this._game.stage.context.globalAlpha = this.alpha;
} }
//if (this.flip === true)
//{
// this.context.save();
// this.context.translate(game.canvas.width, 0);
// this.context.scale(-1, 1);
//}
this._sx = 0; this._sx = 0;
this._sy = 0; this._sy = 0;
this._sw = this.bounds.width; this._sw = this.bounds.width;
@@ -228,15 +223,24 @@ module Phaser {
this._dy -= (camera.worldView.y * this.scrollFactor.y); this._dy -= (camera.worldView.y * this.scrollFactor.y);
} }
// Rotation // Rotation - needs to work from origin point really, but for now from center
if (this.angle !== 0) if (this.angle !== 0 || this.rotationOffset !== 0 || this.flipped == true)
{ {
this._game.stage.context.save(); this._game.stage.context.save();
//this._game.stage.context.translate(this._dx + (this._dw / 2) - this.origin.x, this._dy + (this._dh / 2) - this.origin.y);
this._game.stage.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2)); this._game.stage.context.translate(this._dx + (this._dw / 2), this._dy + (this._dh / 2));
this._game.stage.context.rotate(this.angle * (Math.PI / 180));
if (this.renderRotation == true && (this.angle !== 0 || this.rotationOffset !== 0))
{
this._game.stage.context.rotate((this.rotationOffset + this.angle) * (Math.PI / 180));
}
this._dx = -(this._dw / 2); this._dx = -(this._dw / 2);
this._dy = -(this._dh / 2); this._dy = -(this._dh / 2);
if (this.flipped == true)
{
this._game.stage.context.scale(-1, 1);
}
} }
this._sx = Math.round(this._sx); this._sx = Math.round(this._sx);
@@ -285,16 +289,15 @@ module Phaser {
this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh); this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh);
} }
if (this.renderDebug) if (this.flipped === true || this.rotation !== 0 || this.rotationOffset !== 0)
{ {
this.renderBounds(); //this._game.stage.context.translate(0, 0);
this._game.stage.context.restore();
} }
//if (this.flip === true || this.rotation !== 0) if (this.renderDebug)
if (this.rotation !== 0)
{ {
this._game.stage.context.translate(0, 0); this.renderBounds(camera, cameraOffsetX, cameraOffsetY);
this._game.stage.context.restore();
} }
if (globalAlpha > -1) if (globalAlpha > -1)
@@ -306,7 +309,11 @@ module Phaser {
} }
private renderBounds() { // Renders the bounding box around this Sprite and the contact points. Useful for visually debugging.
private renderBounds(camera:Camera, cameraOffsetX:number, cameraOffsetY:number) {
this._dx = cameraOffsetX + (this.bounds.topLeft.x - camera.worldView.x);
this._dy = cameraOffsetY + (this.bounds.topLeft.y - camera.worldView.y);
this._game.stage.context.fillStyle = this.renderDebugColor; this._game.stage.context.fillStyle = this.renderDebugColor;
this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh); this._game.stage.context.fillRect(this._dx, this._dy, this._dw, this._dh);
+31
View File
@@ -0,0 +1,31 @@
/// <reference path="../Game.d.ts" />
/// <reference path="GameObject.d.ts" />
/// <reference path="../system/TilemapLayer.d.ts" />
/// <reference path="../system/Tile.d.ts" />
module Phaser {
class Tilemap extends GameObject {
constructor(game: Game, key: string, mapData: string, format: number, resizeWorld?: bool, tileWidth?: number, tileHeight?: number);
static FORMAT_CSV: number;
static FORMAT_TILED_JSON: number;
public tiles: Tile[];
public layers: TilemapLayer[];
public currentLayer: TilemapLayer;
public collisionLayer: TilemapLayer;
public mapFormat: number;
public update(): void;
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): void;
private parseCSV(data, key, tileWidth, tileHeight);
private parseTiledJSON(data, key);
private generateTiles(qty);
public widthInPixels : number;
public heightInPixels : number;
public setCollisionRange(start: number, end: number, collision?: number, resetCollisions?: bool): void;
public setCollisionByIndex(values: number[], collision?: number, resetCollisions?: bool): void;
public getTile(x: number, y: number, layer?: number): Tile;
public getTileFromWorldXY(x: number, y: number, layer?: number): Tile;
public getTileFromInputXY(layer?: number): Tile;
public getTileOverlaps(object: GameObject): bool;
public collide(objectOrGroup?, callback?): bool;
public collideGameObject(object: GameObject): bool;
}
}
+206 -179
View File
@@ -1,271 +1,298 @@
/// <reference path="../Game.ts" /> /// <reference path="../Game.ts" />
/// <reference path="GameObject.ts" /> /// <reference path="GameObject.ts" />
/// <reference path="../system/TilemapLayer.ts" />
/// <reference path="../system/Tile.ts" /> /// <reference path="../system/Tile.ts" />
/// <reference path="../system/TilemapBuffer.ts" />
/** /**
* Phaser - Tilemap * 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. * 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 TilemapBuffer for each camera in the world. * Internally it creates a TilemapLayer for each layer in the tilemap.
*/ */
module Phaser { module Phaser {
export class Tilemap extends GameObject { export class Tilemap extends GameObject {
constructor(game: Game, key: string, mapData: string, format: number, tileWidth?: number = 0, tileHeight?: number = 0) { constructor(game: Game, key: string, mapData: string, format: number, resizeWorld: bool = true, tileWidth?: number = 0, tileHeight?: number = 0) {
super(game); super(game);
this._texture = this._game.cache.getImage(key);
this._tilemapBuffers = [];
this.isGroup = false; this.isGroup = false;
this.tileWidth = tileWidth; this.tiles = [];
this.tileHeight = tileHeight; this.layers = [];
this.boundsInTiles = new Rectangle();
this.mapFormat = format; this.mapFormat = format;
switch (format) switch (format)
{ {
case Tilemap.FORMAT_CSV: case Tilemap.FORMAT_CSV:
this.parseCSV(game.cache.getText(mapData)); this.parseCSV(game.cache.getText(mapData), key, tileWidth, tileHeight);
break; break;
case Tilemap.FORMAT_TILED_JSON: case Tilemap.FORMAT_TILED_JSON:
this.parseTiledJSON(game.cache.getText(mapData)); this.parseTiledJSON(game.cache.getText(mapData), key);
break; break;
} }
this.parseTileOffsets(); if (this.currentLayer && resizeWorld)
this.createTilemapBuffers(); {
this._game.world.setSize(this.currentLayer.widthInPixels, this.currentLayer.heightInPixels, true);
}
} }
private _texture; private _tempCollisionData;
private _tileOffsets;
private _tilemapBuffers: TilemapBuffer[];
private _dx: number = 0;
private _dy: number = 0;
public static FORMAT_CSV: number = 0; public static FORMAT_CSV: number = 0;
public static FORMAT_TILED_JSON: number = 1; public static FORMAT_TILED_JSON: number = 1;
public mapData; public tiles : Tile[];
public layers : TilemapLayer[];
public currentLayer: TilemapLayer;
public collisionLayer: TilemapLayer;
public collisionCallback = null;
public collisionCallbackContext;
public mapFormat: number; public mapFormat: number;
public boundsInTiles: Rectangle;
public tileWidth: number; public update() {
public tileHeight: number; }
public widthInTiles: number = 0; public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number) {
public heightInTiles: number = 0;
public widthInPixels: number = 0; if (this.cameraBlacklist.indexOf(camera.ID) == -1)
public heightInPixels: number = 0; {
// Loop through the layers
for (var i = 0; i < this.layers.length; i++)
{
this.layers[i].render(camera, cameraOffsetX, cameraOffsetY);
}
}
// How many extra tiles to draw around the edge of the screen (for fast scrolling games, or to optimise mobile performance try increasing this) }
// The number is the amount of extra tiles PER SIDE, so a value of 10 would be (10 tiles + screen size + 10 tiles)
public tileBoundary: number = 10;
private parseCSV(data: string) { private parseCSV(data: string, key: string, tileWidth: number, tileHeight: number) {
//console.log('parseMapData'); var layer: TilemapLayer = new TilemapLayer(this._game, this, key, Tilemap.FORMAT_CSV, 'TileLayerCSV' + this.layers.length.toString(), tileWidth, tileHeight);
this.mapData = [];
// Trim any rogue whitespace from the data // Trim any rogue whitespace from the data
data = data.trim(); data = data.trim();
var rows = data.split("\n"); var rows = data.split("\n");
//console.log('rows', rows);
for (var i = 0; i < rows.length; i++) for (var i = 0; i < rows.length; i++)
{ {
var column = rows[i].split(","); var column = rows[i].split(",");
//console.log('column', column);
var output = [];
if (column.length > 0) if (column.length > 0)
{ {
// Set the width based on the first row layer.addColumn(column);
if (this.widthInTiles == 0)
{
// Maybe -1?
this.widthInTiles = column.length;
}
// We have a new row of tiles
this.heightInTiles++;
// Parse it
for (var c = 0; c < column.length; c++)
{
output[c] = parseInt(column[c]);
}
this.mapData.push(output);
} }
} }
//console.log('final map array'); layer.updateBounds();
//console.log(this.mapData); var tileQuantity = layer.parseTileOffsets();
if (this.widthInTiles > 0) this.currentLayer = layer;
{ this.collisionLayer = layer;
this.widthInPixels = this.tileWidth * this.widthInTiles;
}
if (this.heightInTiles > 0) this.layers.push(layer);
{
this.heightInPixels = this.tileHeight * this.heightInTiles;
}
this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles); this.generateTiles(tileQuantity);
} }
private parseTiledJSON(data: string) { private parseTiledJSON(data: string, key: string) {
//console.log('parseTiledJSON');
this.mapData = [];
// Trim any rogue whitespace from the data // Trim any rogue whitespace from the data
data = data.trim(); data = data.trim();
// We ought to change this soon, so we have layer support, but for now let's just get it working
var json = JSON.parse(data); var json = JSON.parse(data);
// Right now we assume no errors at all with the parsing (safe I know) for (var i = 0; i < json.layers.length; i++)
this.tileWidth = json.tilewidth;
this.tileHeight = json.tileheight;
// Parse the first layer only
this.widthInTiles = json.layers[0].width;
this.heightInTiles = json.layers[0].height;
this.widthInPixels = this.widthInTiles * this.tileWidth;
this.heightInPixels = this.heightInTiles * this.tileHeight;
this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles);
//console.log('width in tiles', this.widthInTiles);
//console.log('height in tiles', this.heightInTiles);
//console.log('width in px', this.widthInPixels);
//console.log('height in px', this.heightInPixels);
// Now let's get the data
var c = 0;
var row;
for (var i = 0; i < json.layers[0].data.length; i++)
{ {
if (c == 0) var layer: TilemapLayer = new TilemapLayer(this._game, this, key, Tilemap.FORMAT_TILED_JSON, json.layers[i].name, json.tilewidth, json.tileheight);
layer.alpha = json.layers[i].opacity;
layer.visible = json.layers[i].visible;
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++)
{ {
row = []; if (c == 0)
{
row = [];
}
row.push(json.layers[i].data[t]);
c++;
if (c == json.layers[i].width)
{
layer.addColumn(row);
c = 0;
}
} }
row.push(json.layers[0].data[i]); layer.updateBounds();
c++; var tileQuantity = layer.parseTileOffsets();
if (c == this.widthInTiles) this.currentLayer = layer;
this.collisionLayer = layer;
this.layers.push(layer);
}
this.generateTiles(tileQuantity);
}
private generateTiles(qty:number) {
for (var i = 0; i < qty; i++)
{
this.tiles.push(new Tile(this._game, this, i, this.currentLayer.tileWidth, this.currentLayer.tileHeight));
}
}
public get widthInPixels(): number {
return this.currentLayer.widthInPixels;
}
public get heightInPixels(): number {
return this.currentLayer.heightInPixels;
}
// Tile Collision
public setCollisionCallback(context, callback) {
this.collisionCallbackContext = context;
this.collisionCallback = callback;
}
public setCollisionRange(start: number, end: number, collision?:number = Collision.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) {
for (var i = start; i < end; i++)
{
this.tiles[i].setCollision(collision, resetCollisions, separateX, separateY);
}
}
public setCollisionByIndex(values:number[], collision?:number = Collision.ANY, resetCollisions?: bool = false, separateX?: bool = true, separateY?: bool = true) {
for (var i = 0; i < values.length; i++)
{
this.tiles[values[i]].setCollision(collision, resetCollisions, separateX, separateY);
}
}
// Tile Management
public getTileByIndex(value: number):Tile {
if (this.tiles[value])
{
return this.tiles[value];
}
return null;
}
public getTile(x: number, y: number, layer?: number = 0):Tile {
return this.tiles[this.layers[layer].getTileIndex(x, y)];
}
public getTileFromWorldXY(x: number, y: number, layer?: number = 0):Tile {
return this.tiles[this.layers[layer].getTileFromWorldXY(x, y)];
}
public getTileFromInputXY(layer?: number = 0):Tile {
return this.tiles[this.layers[layer].getTileFromWorldXY(this._game.input.worldX, this._game.input.worldY)];
}
public getTileOverlaps(object: GameObject) {
return this.currentLayer.getTileOverlaps(object);
}
// COLLIDE
public collide(objectOrGroup = null, callback = null, 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);
}
}
public collideGameObject(object: GameObject): bool {
if (object !== this && object.immovable == false && object.exists == true && object.allowCollisions != Collision.NONE)
{
this._tempCollisionData = this.collisionLayer.getTileOverlaps(object);
if (this.collisionCallback !== null && this._tempCollisionData.length > 0)
{ {
this.mapData.push(row); this.collisionCallback.call(this.collisionCallbackContext, object, this._tempCollisionData);
c = 0;
} }
return true;
} }
else
//console.log('mapData');
//console.log(this.mapData);
}
public getMapSegment(area: Rectangle) {
}
private createTilemapBuffers() {
var cams = this._game.world.getAllCameras();
for (var i = 0; i < cams.length; i++)
{
this._tilemapBuffers[cams[i].ID] = new TilemapBuffer(this._game, cams[i], this, this._texture, this._tileOffsets);
}
}
private parseTileOffsets() {
this._tileOffsets = [];
var i = 0;
if (this.mapFormat == Tilemap.FORMAT_TILED_JSON)
{
// For some reason Tiled counts from 1 not 0
this._tileOffsets[0] = null;
i = 1;
}
for (var ty = 0; ty < this._texture.height; ty += this.tileHeight)
{
for (var tx = 0; tx < this._texture.width; tx += this.tileWidth)
{
this._tileOffsets[i] = { x: tx, y: ty };
i++;
}
}
}
/*
// Use a Signal?
public addTilemapBuffers(camera:Camera) {
console.log('added new camera to tilemap');
this._tilemapBuffers[camera.ID] = new TilemapBuffer(this._game, camera, this, this._texture, this._tileOffsets);
}
*/
public update() {
// Check if any of the cameras have scrolled far enough for us to need to refresh a TilemapBuffer
this._tilemapBuffers[0].update();
}
public renderDebugInfo(x: number, y: number, color?: string = 'rgb(255,255,255)') {
this._tilemapBuffers[0].renderDebugInfo(x, y, color);
}
public render(camera: Camera, cameraOffsetX: number, cameraOffsetY: number): bool {
if (this.visible === false || this.scale.x == 0 || this.scale.y == 0 || this.alpha < 0.1)
{ {
return false; return false;
} }
this._dx = cameraOffsetX + (this.bounds.x - camera.worldView.x); }
this._dy = cameraOffsetY + (this.bounds.y - camera.worldView.y);
this._dx = Math.round(this._dx); public putTile(x: number, y: number, index: number, layer?: number = 0) {
this._dy = Math.round(this._dy);
if (this._tilemapBuffers[camera.ID]) this.layers[layer].putTile(x, y, index);
{
//this._tilemapBuffers[camera.ID].render(this._dx, this._dy);
this._tilemapBuffers[camera.ID].render(cameraOffsetX, cameraOffsetY);
}
return true;
} }
// Set current layer
// Set layer order?
// Delete tiles of certain type
// Erase tiles
} }
} }
+34
View File
@@ -0,0 +1,34 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Circle {
constructor(x?: number, y?: number, diameter?: number);
private _diameter;
private _radius;
public x: number;
public y: number;
public diameter : number;
public radius : number;
public circumference(): number;
public bottom : number;
public left : number;
public right : number;
public top : number;
public area : number;
public isEmpty : bool;
public intersectCircleLine(line: Line): bool;
public clone(output?: Circle): Circle;
public contains(x: number, y: number): bool;
public containsPoint(point: Point): bool;
public containsCircle(circle: Circle): bool;
public copyFrom(source: Circle): Circle;
public copyTo(target: Circle): Circle;
public distanceTo(target: any, round?: bool): number;
public equals(toCompare: Circle): bool;
public intersects(toIntersect: Circle): bool;
public circumferencePoint(angle: number, asDegrees?: bool, output?: Point): Point;
public offset(dx: number, dy: number): Circle;
public offsetPoint(point: Point): Circle;
public setTo(x: number, y: number, diameter: number): Circle;
public toString(): string;
}
}
+1 -1
View File
@@ -262,7 +262,7 @@ module Phaser {
**/ **/
get isEmpty(): bool { get isEmpty(): bool {
if (this._diameter < 1) if (this._diameter <= 0)
{ {
return true; return true;
} }
+15
View File
@@ -0,0 +1,15 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class IntersectResult {
public result: bool;
public x: number;
public y: number;
public x1: number;
public y1: number;
public x2: number;
public y2: number;
public width: number;
public height: number;
public setTo(x1: number, y1: number, x2?: number, y2?: number, width?: number, height?: number): void;
}
}
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Line {
constructor(x1?: number, y1?: number, x2?: number, y2?: number);
public x1: number;
public y1: number;
public x2: number;
public y2: number;
public clone(output?: Line): Line;
public copyFrom(source: Line): Line;
public copyTo(target: Line): Line;
public setTo(x1?: number, y1?: number, x2?: number, y2?: number): Line;
public width : number;
public height : number;
public length : number;
public getY(x: number): number;
public angle : number;
public slope : number;
public perpSlope : number;
public yIntercept : number;
public isPointOnLine(x: number, y: number): bool;
public isPointOnLineSegment(x: number, y: number): bool;
public intersectLineLine(line): any;
public perp(x: number, y: number, output?: Line): Line;
public toString(): string;
}
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class MicroPoint {
constructor(x?: number, y?: number, parent?: any);
private _x;
private _y;
public parent: any;
public x : number;
public y : number;
public copyFrom(source: any): MicroPoint;
public copyTo(target: any): MicroPoint;
public setTo(x: number, y: number, callParent?: bool): MicroPoint;
public equals(toCompare): bool;
public toString(): string;
}
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Point {
constructor(x?: number, y?: number);
public x: number;
public y: number;
public add(toAdd: Point, output?: Point): Point;
public addTo(x?: number, y?: number): Point;
public subtractFrom(x?: number, y?: number): Point;
public invert(): Point;
public clamp(min: number, max: number): Point;
public clampX(min: number, max: number): Point;
public clampY(min: number, max: number): Point;
public clone(output?: Point): Point;
public copyFrom(source: Point): Point;
public copyTo(target: Point): Point;
public distanceTo(target: Point, round?: bool): number;
static distanceBetween(pointA: Point, pointB: Point, round?: bool): number;
public distanceCompare(target: Point, distance: number): bool;
public equals(toCompare: Point): bool;
public interpolate(pointA, pointB, f): void;
public offset(dx: number, dy: number): Point;
public polar(length, angle): void;
public setTo(x: number, y: number): Point;
public subtract(point: Point, output?: Point): Point;
public toString(): string;
}
}
+19
View File
@@ -0,0 +1,19 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Quad {
constructor(x?: number, y?: number, width?: number, height?: number);
public x: number;
public y: number;
public width: number;
public height: number;
public setTo(x: number, y: number, width: number, height: number): Quad;
public left : number;
public right : number;
public top : number;
public bottom : number;
public halfWidth : number;
public halfHeight : number;
public intersects(q, t?: number): bool;
public toString(): string;
}
}
+106
View File
@@ -0,0 +1,106 @@
/// <reference path="../Game.ts" />
/**
* Phaser - Quad
*
* A Quad object is an area defined by its position, as indicated by its top-left corner (x,y) and width and height.
* Very much like a Rectangle only without all of the additional methods and properties of that class.
*/
module Phaser {
export class Quad {
/**
* Creates a new Quad object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created.
* @class Quad
* @constructor
* @param {Number} x The x coordinate of the top-left corner of the quad.
* @param {Number} y The y coordinate of the top-left corner of the quad.
* @param {Number} width The width of the quad.
* @param {Number} height The height of the quad.
* @return {Quad } This object
**/
constructor(x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
this.setTo(x, y, width, height);
}
public x: number;
public y: number;
public width: number;
public height: number;
/**
* Sets the Quad to the specified size.
* @method setTo
* @param {Number} x The x coordinate of the top-left corner of the quad.
* @param {Number} y The y coordinate of the top-left corner of the quad.
* @param {Number} width The width of the quad.
* @param {Number} height The height of the quad.
* @return {Quad} This object
**/
public setTo(x: number, y: number, width: number, height: number): Quad {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
return this;
}
public get left(): number {
return this.x;
}
public get right(): number {
return this.x + this.width;
}
public get top(): number {
return this.y;
}
public get bottom(): number {
return this.y + this.height;
}
public get halfWidth(): number {
return this.width / 2;
}
public get halfHeight(): number {
return this.height / 2;
}
/**
* 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.
**/
public intersects(q, t?: number = 0): bool {
return !(q.left > this.right + t || q.right < this.left - t || q.top > this.bottom + t || q.bottom < this.top - t);
}
/**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the object.
**/
public toString(): string {
return "[{Quad (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
}
}
}
+57
View File
@@ -0,0 +1,57 @@
/// <reference path="../Game.d.ts" />
/// <reference path="MicroPoint.d.ts" />
module Phaser {
class Rectangle {
constructor(x?: number, y?: number, width?: number, height?: number);
private _tempX;
private _tempY;
private _tempWidth;
private _tempHeight;
public x : number;
public y : number;
public topLeft: MicroPoint;
public topCenter: MicroPoint;
public topRight: MicroPoint;
public leftCenter: MicroPoint;
public center: MicroPoint;
public rightCenter: MicroPoint;
public bottomLeft: MicroPoint;
public bottomCenter: MicroPoint;
public bottomRight: MicroPoint;
private _width;
private _height;
private _halfWidth;
private _halfHeight;
public length: number;
public updateBounds(): void;
public width : number;
public height : number;
public halfWidth : number;
public halfHeight : number;
public bottom : number;
public left : number;
public right : number;
public size(output?: Point): Point;
public volume : number;
public perimeter : number;
public top : number;
public clone(output?: Rectangle): Rectangle;
public contains(x: number, y: number): bool;
public containsPoint(point: any): bool;
public containsRect(rect: Rectangle): bool;
public copyFrom(source: Rectangle): Rectangle;
public copyTo(target: Rectangle): Rectangle;
public equals(toCompare: Rectangle): bool;
public inflate(dx: number, dy: number): Rectangle;
public inflatePoint(point: Point): Rectangle;
public intersection(toIntersect: Rectangle, output?: Rectangle): Rectangle;
public intersects(r2: Rectangle, t?: number): bool;
public isEmpty : bool;
public offset(dx: number, dy: number): Rectangle;
public offsetPoint(point: Point): Rectangle;
public setEmpty(): Rectangle;
public setTo(x: number, y: number, width: number, height: number): Rectangle;
public union(toUnion: Rectangle, output?: Rectangle): Rectangle;
public toString(): string;
}
}
+4 -3
View File
@@ -12,13 +12,14 @@ module Phaser {
export class Rectangle { export class Rectangle {
/** /**
* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created. * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters.
* If you call this function without parameters, a rectangle with x, y, width, and height properties set to 0 is created.
* @class Rectangle * @class Rectangle
* @constructor * @constructor
* @param {Number} x The x coordinate of the top-left corner of the rectangle. * @param {Number} x The x coordinate of the top-left corner of the rectangle.
* @param {Number} y The y coordinate of the top-left corner of the rectangle. * @param {Number} y The y coordinate of the top-left corner of the rectangle.
* @param {Number} width The width of the rectangle in pixels. * @param {Number} width The width of the rectangle.
* @param {Number} height The height of the rectangle in pixels. * @param {Number} height The height of the rectangle.
* @return {Rectangle} This rectangle object * @return {Rectangle} This rectangle object
**/ **/
constructor(x: number = 0, y: number = 0, width: number = 0, height: number = 0) { constructor(x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
+19 -19
View File
@@ -1,19 +1,19 @@
/** /**
* Phaser * Phaser
* *
* v0.9.1 - April 19th 2013 * v0.9.5 - April 28th 2013
* *
* A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi. * A small and feature-packed 2D canvas game framework born from the firey pits of Flixel and Kiwi.
* *
* Richard Davey (@photonstorm) * Richard Davey (@photonstorm)
* *
* Many thanks to Adam Saltsman (@ADAMATOMIC) for the original Flixel AS3 code on which Phaser is based. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel on which Phaser took a lot of inspiration.
* *
* "If you want your children to be intelligent, read them fairy tales." * "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales." * "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein * -- Albert Einstein
*/ */
var Phaser; var Phaser;
(function (Phaser) { (function (Phaser) {
Phaser.VERSION = 'Phaser version 0.9.1'; Phaser.VERSION = 'Phaser version 0.9.5';
})(Phaser || (Phaser = {})); })(Phaser || (Phaser = {}));
+80
View File
@@ -0,0 +1,80 @@
/// <reference path="../gameobjects/Sprite.d.ts" />
/// <reference path="../Game.d.ts" />
module Phaser {
class Camera {
constructor(game: Game, id: number, x: number, y: number, width: number, height: number);
private _game;
private _clip;
private _stageX;
private _stageY;
private _rotation;
private _target;
private _sx;
private _sy;
private _fxFlashColor;
private _fxFlashComplete;
private _fxFlashDuration;
private _fxFlashAlpha;
private _fxFadeColor;
private _fxFadeComplete;
private _fxFadeDuration;
private _fxFadeAlpha;
private _fxShakeIntensity;
private _fxShakeDuration;
private _fxShakeComplete;
private _fxShakeOffset;
private _fxShakeDirection;
private _fxShakePrevX;
private _fxShakePrevY;
static STYLE_LOCKON: number;
static STYLE_PLATFORMER: number;
static STYLE_TOPDOWN: number;
static STYLE_TOPDOWN_TIGHT: number;
static SHAKE_BOTH_AXES: number;
static SHAKE_HORIZONTAL_ONLY: number;
static SHAKE_VERTICAL_ONLY: number;
public ID: number;
public worldView: Rectangle;
public totalSpritesRendered: number;
public scale: MicroPoint;
public scroll: MicroPoint;
public bounds: Rectangle;
public deadzone: Rectangle;
public showBorder: bool;
public borderColor: string;
public opaque: bool;
private _bgColor;
private _bgTexture;
private _bgTextureRepeat;
public showShadow: bool;
public shadowColor: string;
public shadowBlur: number;
public shadowOffset: MicroPoint;
public visible: bool;
public alpha: number;
public inputX: number;
public inputY: number;
public fx: FXManager;
public flash(color?: number, duration?: number, onComplete?, force?: bool): void;
public fade(color?: number, duration?: number, onComplete?, force?: bool): void;
public shake(intensity?: number, duration?: number, onComplete?, force?: bool, direction?: number): void;
public stopFX(): void;
public follow(target: Sprite, style?: number): void;
public focusOnXY(x: number, y: number): void;
public focusOn(point): void;
public setBounds(x?: number, y?: number, width?: number, height?: number): void;
public update(): void;
public render(): void;
public backgroundColor : string;
public setTexture(key: string, repeat?: string): void;
public setPosition(x: number, y: number): void;
public setSize(width: number, height: number): void;
public renderDebugInfo(x: number, y: number, color?: string): void;
public x : number;
public y : number;
public width : number;
public height : number;
public rotation : number;
private checkClip();
}
}
+43 -251
View File
@@ -29,6 +29,7 @@ module Phaser {
this.ID = id; this.ID = id;
this._stageX = x; this._stageX = x;
this._stageY = y; this._stageY = y;
this.fx = new FXManager(this._game, this);
// The view into the world canvas we wish to render // The view into the world canvas we wish to render
this.worldView = new Rectangle(0, 0, width, height); this.worldView = new Rectangle(0, 0, width, height);
@@ -47,42 +48,21 @@ module Phaser {
private _sx: number = 0; private _sx: number = 0;
private _sy: number = 0; private _sy: number = 0;
private _fxFlashColor: string;
private _fxFlashComplete = null;
private _fxFlashDuration: number = 0;
private _fxFlashAlpha: number = 0;
private _fxFadeColor: string;
private _fxFadeComplete = null;
private _fxFadeDuration: number = 0;
private _fxFadeAlpha: number = 0;
private _fxShakeIntensity: number = 0;
private _fxShakeDuration: number = 0;
private _fxShakeComplete = null;
private _fxShakeOffset: Point = new Point(0, 0);
private _fxShakeDirection: number = 0;
private _fxShakePrevX: number = 0;
private _fxShakePrevY: number = 0;
public static STYLE_LOCKON: number = 0; public static STYLE_LOCKON: number = 0;
public static STYLE_PLATFORMER: number = 1; public static STYLE_PLATFORMER: number = 1;
public static STYLE_TOPDOWN: number = 2; public static STYLE_TOPDOWN: number = 2;
public static STYLE_TOPDOWN_TIGHT: number = 3; public static STYLE_TOPDOWN_TIGHT: number = 3;
public static SHAKE_BOTH_AXES: number = 0;
public static SHAKE_HORIZONTAL_ONLY: number = 1;
public static SHAKE_VERTICAL_ONLY: number = 2;
public ID: number; public ID: number;
public worldView: Rectangle; public worldView: Rectangle;
public totalSpritesRendered: number; public totalSpritesRendered: number;
public scale: Point = new Point(1, 1); public scale: MicroPoint = new MicroPoint(1, 1);
public scroll: Point = new Point(0, 0); public scroll: MicroPoint = new MicroPoint(0, 0);
public bounds: Rectangle = null; public bounds: Rectangle = null;
public deadzone: Rectangle = null; public deadzone: Rectangle = null;
// Camera Border // Camera Border
public disableClipping: bool = false;
public showBorder: bool = false; public showBorder: bool = false;
public borderColor: string = 'rgb(255,255,255)'; public borderColor: string = 'rgb(255,255,255)';
@@ -96,7 +76,7 @@ module Phaser {
public showShadow: bool = false; public showShadow: bool = false;
public shadowColor: string = 'rgb(0,0,0)'; public shadowColor: string = 'rgb(0,0,0)';
public shadowBlur: number = 10; public shadowBlur: number = 10;
public shadowOffset: Point = new Point(4, 4); public shadowOffset: MicroPoint = new MicroPoint(4, 4);
public visible: bool = true; public visible: bool = true;
public alpha: number = 1; public alpha: number = 1;
@@ -105,122 +85,12 @@ module Phaser {
public inputX: number = 0; public inputX: number = 0;
public inputY: number = 0; public inputY: number = 0;
/** public fx: FXManager;
* The camera is filled with this color and returns to normal at the given duration.
*
* @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white.
* @param Duration How long it takes for the flash to fade.
* @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback.
* @param Force Force an already running flash effect to reset.
*/
public flash(color: number = 0xffffff, duration: number = 1, onComplete = null, force: bool = false) {
if (force === false && this._fxFlashAlpha > 0)
{
// You can't flash again unless you force it
return;
}
if (duration <= 0)
{
duration = 1;
}
var red = color >> 16 & 0xFF;
var green = color >> 8 & 0xFF;
var blue = color & 0xFF;
this._fxFlashColor = 'rgba(' + red + ',' + green + ',' + blue + ',';
this._fxFlashDuration = duration;
this._fxFlashAlpha = 1;
this._fxFlashComplete = onComplete;
}
/**
* The camera is gradually filled with this color.
*
* @param Color The color you want to use in 0xRRGGBB format, i.e. 0xffffff for white.
* @param Duration How long it takes for the flash to fade.
* @param OnComplete An optional function you want to run when the flash finishes. Set to null for no callback.
* @param Force Force an already running flash effect to reset.
*/
public fade(color: number = 0x000000, duration: number = 1, onComplete = null, force: bool = false) {
if (force === false && this._fxFadeAlpha > 0)
{
// You can't fade again unless you force it
return;
}
if (duration <= 0)
{
duration = 1;
}
var red = color >> 16 & 0xFF;
var green = color >> 8 & 0xFF;
var blue = color & 0xFF;
this._fxFadeColor = 'rgba(' + red + ',' + green + ',' + blue + ',';
this._fxFadeDuration = duration;
this._fxFadeAlpha = 0.01;
this._fxFadeComplete = onComplete;
}
/**
* A simple screen-shake effect.
*
* @param Intensity Percentage of screen size representing the maximum distance that the screen can move while shaking.
* @param Duration The length in seconds that the shaking effect should last.
* @param OnComplete A function you want to run when the shake effect finishes.
* @param Force Force the effect to reset (default = true, unlike flash() and fade()!).
* @param Direction Whether to shake on both axes, just up and down, or just side to side (use class constants SHAKE_BOTH_AXES, SHAKE_VERTICAL_ONLY, or SHAKE_HORIZONTAL_ONLY).
*/
public shake(intensity: number = 0.05, duration: number = 0.5, onComplete = null, force: bool = true, direction: number = Camera.SHAKE_BOTH_AXES) {
if (!force && ((this._fxShakeOffset.x != 0) || (this._fxShakeOffset.y != 0)))
{
return;
}
// If a shake is not already running we need to store the offsets here
if (this._fxShakeOffset.x == 0 && this._fxShakeOffset.y == 0)
{
this._fxShakePrevX = this._stageX;
this._fxShakePrevY = this._stageY;
}
this._fxShakeIntensity = intensity;
this._fxShakeDuration = duration;
this._fxShakeComplete = onComplete;
this._fxShakeDirection = direction;
this._fxShakeOffset.setTo(0, 0);
}
/**
* Just turns off all the camera effects instantly.
*/
public stopFX() {
this._fxFlashAlpha = 0;
this._fxFadeAlpha = 0;
if (this._fxShakeDuration !== 0)
{
this._fxShakeDuration = 0;
this._fxShakeOffset.setTo(0, 0);
this._stageX = this._fxShakePrevX;
this._stageY = this._fxShakePrevY;
}
}
public follow(target: Sprite, style?: number = Camera.STYLE_LOCKON) { public follow(target: Sprite, style?: number = Camera.STYLE_LOCKON) {
this._target = target; this._target = target;
var helper: number; var helper: number;
switch (style) switch (style)
@@ -256,7 +126,7 @@ module Phaser {
} }
public focusOn(point: Point) { public focusOn(point) {
point.x += (point.x > 0) ? 0.0000001 : -0.0000001; point.x += (point.x > 0) ? 0.0000001 : -0.0000001;
point.y += (point.y > 0) ? 0.0000001 : -0.0000001; point.y += (point.y > 0) ? 0.0000001 : -0.0000001;
@@ -269,29 +139,29 @@ module Phaser {
/** /**
* Specify the boundaries of the world or where the camera is allowed to move. * 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 x The smallest X value of your world (usually 0).
* @param Y The smallest Y 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 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). * @param height The largest Y value of your world (usually the world height).
* @param UpdateWorld Whether the global quad-tree's dimensions should be updated to match (default: false).
*/ */
public setBounds(X: number = 0, Y: number = 0, Width: number = 0, Height: number = 0, UpdateWorld: bool = false) { public setBounds(x: number = 0, y: number = 0, width: number = 0, height: number = 0) {
if (this.bounds == null) if (this.bounds == null)
{ {
this.bounds = new Rectangle(); this.bounds = new Rectangle();
} }
this.bounds.setTo(X, Y, Width, Height); this.bounds.setTo(x, y, width, height);
//if(UpdateWorld) this.scroll.setTo(0, 0);
// G.worldBounds.copyFrom(bounds);
this.update(); this.update();
} }
public update() { public update() {
this.fx.preUpdate();
if (this._target !== null) if (this._target !== null)
{ {
if (this.deadzone == null) if (this.deadzone == null)
@@ -335,7 +205,7 @@ module Phaser {
} }
// Make sure we didn't go outside the camera's bounds // Make sure we didn't go outside the cameras bounds
if (this.bounds !== null) if (this.bounds !== null)
{ {
if (this.scroll.x < this.bounds.left) if (this.scroll.x < this.bounds.left)
@@ -345,7 +215,7 @@ module Phaser {
if (this.scroll.x > this.bounds.right - this.width) if (this.scroll.x > this.bounds.right - this.width)
{ {
this.scroll.x = this.bounds.right - this.width; this.scroll.x = (this.bounds.right - this.width) + 1;
} }
if (this.scroll.y < this.bounds.top) if (this.scroll.y < this.bounds.top)
@@ -355,7 +225,7 @@ module Phaser {
if (this.scroll.y > this.bounds.bottom - this.height) if (this.scroll.y > this.bounds.bottom - this.height)
{ {
this.scroll.y = this.bounds.bottom - this.height; this.scroll.y = (this.bounds.bottom - this.height) + 1;
} }
} }
@@ -366,101 +236,27 @@ module Phaser {
this.inputX = this.worldView.x + this._game.input.x; this.inputX = this.worldView.x + this._game.input.x;
this.inputY = this.worldView.y + this._game.input.y; this.inputY = this.worldView.y + this._game.input.y;
// Update the Flash effect this.fx.postUpdate();
if (this._fxFlashAlpha > 0)
{
this._fxFlashAlpha -= this._game.time.elapsed / this._fxFlashDuration;
this._fxFlashAlpha = this._game.math.roundTo(this._fxFlashAlpha, -2);
if (this._fxFlashAlpha <= 0)
{
this._fxFlashAlpha = 0;
if (this._fxFlashComplete !== null)
{
this._fxFlashComplete();
}
}
}
// Update the Fade effect
if (this._fxFadeAlpha > 0)
{
this._fxFadeAlpha += this._game.time.elapsed / this._fxFadeDuration;
this._fxFadeAlpha = this._game.math.roundTo(this._fxFadeAlpha, -2);
if (this._fxFadeAlpha >= 1)
{
this._fxFadeAlpha = 1;
if (this._fxFadeComplete !== null)
{
this._fxFadeComplete();
}
}
}
// Update the "shake" special effect
if (this._fxShakeDuration > 0)
{
this._fxShakeDuration -= this._game.time.elapsed;
this._fxShakeDuration = this._game.math.roundTo(this._fxShakeDuration, -2);
if (this._fxShakeDuration <= 0)
{
this._fxShakeDuration = 0;
this._fxShakeOffset.setTo(0, 0);
this._stageX = this._fxShakePrevX;
this._stageY = this._fxShakePrevY;
if (this._fxShakeComplete != null)
{
this._fxShakeComplete();
}
}
else
{
if ((this._fxShakeDirection == Camera.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Camera.SHAKE_HORIZONTAL_ONLY))
{
//this._fxShakeOffset.x = ((this._game.math.random() * this._fxShakeIntensity * this.worldView.width * 2 - this._fxShakeIntensity * this.worldView.width) * this._zoom;
this._fxShakeOffset.x = (this._game.math.random() * this._fxShakeIntensity * this.worldView.width * 2 - this._fxShakeIntensity * this.worldView.width);
}
if ((this._fxShakeDirection == Camera.SHAKE_BOTH_AXES) || (this._fxShakeDirection == Camera.SHAKE_VERTICAL_ONLY))
{
//this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this.worldView.height * 2 - this._fxShakeIntensity * this.worldView.height) * this._zoom;
this._fxShakeOffset.y = (this._game.math.random() * this._fxShakeIntensity * this.worldView.height * 2 - this._fxShakeIntensity * this.worldView.height);
}
}
}
} }
public render() { public render() {
if (this.visible === false && this.alpha < 0.1) if (this.visible === false || this.alpha < 0.1)
{ {
return; return;
} }
if ((this._fxShakeOffset.x != 0) || (this._fxShakeOffset.y != 0))
{
//this._stageX = this._fxShakePrevX + (this.worldView.halfWidth * this._zoom) + this._fxShakeOffset.x;
//this._stageY = this._fxShakePrevY + (this.worldView.halfHeight * this._zoom) + this._fxShakeOffset.y;
this._stageX = this._fxShakePrevX + (this.worldView.halfWidth) + this._fxShakeOffset.x;
this._stageY = this._fxShakePrevY + (this.worldView.halfHeight) + this._fxShakeOffset.y;
//console.log('shake', this._fxShakeDuration, this._fxShakeIntensity, this._fxShakeOffset.x, this._fxShakeOffset.y);
}
//if (this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1) //if (this._rotation !== 0 || this._clip || this.scale.x !== 1 || this.scale.y !== 1)
//{ //{
//this._game.stage.context.save(); //this._game.stage.context.save();
//} //}
// It may be safe/quicker to just save the context every frame regardless // It may be safer/quicker to just save the context every frame regardless (needs testing on mobile)
this._game.stage.context.save(); this._game.stage.context.save();
this.fx.preRender(this, this._stageX, this._stageY, this.worldView.width, this.worldView.height);
if (this.alpha !== 1) if (this.alpha !== 1)
{ {
this._game.stage.context.globalAlpha = this.alpha; this._game.stage.context.globalAlpha = this.alpha;
@@ -496,7 +292,6 @@ module Phaser {
this._game.stage.context.translate(-(this._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight)); this._game.stage.context.translate(-(this._sx + this.worldView.halfWidth), -(this._sy + this.worldView.halfHeight));
} }
// Background // Background
if (this.opaque == true) if (this.opaque == true)
{ {
@@ -520,8 +315,10 @@ module Phaser {
this._game.stage.context.shadowOffsetY = 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 // Clip the camera so we don't get sprites appearing outside the edges
if (this._clip) if (this._clip && this.disableClipping == false)
{ {
this._game.stage.context.beginPath(); this._game.stage.context.beginPath();
this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height); this._game.stage.context.rect(this._sx, this._sy, this.worldView.width, this.worldView.height);
@@ -529,8 +326,6 @@ module Phaser {
this._game.stage.context.clip(); this._game.stage.context.clip();
} }
//this.totalSpritesRendered = this._game.world.renderSpritesInCamera(this.worldView, sx, sy);
//this._game.world.group.render(this.worldView, this.worldView.x, this.worldView.y, sx, sy);
this._game.world.group.render(this, this._sx, this._sy); this._game.world.group.render(this, this._sx, this._sy);
if (this.showBorder) if (this.showBorder)
@@ -541,33 +336,19 @@ module Phaser {
this._game.stage.context.stroke(); this._game.stage.context.stroke();
} }
// "Flash" FX
if (this._fxFlashAlpha > 0)
{
this._game.stage.context.fillStyle = this._fxFlashColor + this._fxFlashAlpha + ')';
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
}
// "Fade" FX
if (this._fxFadeAlpha > 0)
{
this._game.stage.context.fillStyle = this._fxFadeColor + this._fxFadeAlpha + ')';
this._game.stage.context.fillRect(this._sx, this._sy, this.worldView.width, this.worldView.height);
}
// Scale off // Scale off
if (this.scale.x !== 1 || this.scale.y !== 1) if (this.scale.x !== 1 || this.scale.y !== 1)
{ {
this._game.stage.context.scale(1, 1); this._game.stage.context.scale(1, 1);
} }
if (this._rotation !== 0 || this._clip) 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.translate(0, 0);
//this._game.stage.context.restore();
} }
// maybe just do this every frame regardless?
this._game.stage.context.restore(); this._game.stage.context.restore();
if (this.alpha !== 1) if (this.alpha !== 1)
@@ -607,7 +388,6 @@ module Phaser {
this.worldView.width = width; this.worldView.width = width;
this.worldView.height = height; this.worldView.height = height;
this.checkClip(); this.checkClip();
} }
@@ -649,6 +429,12 @@ module Phaser {
} }
public set width(value: number) { public set width(value: number) {
if (value > this._game.stage.width)
{
value = this._game.stage.width;
}
this.worldView.width = value; this.worldView.width = value;
this.checkClip(); this.checkClip();
} }
@@ -658,6 +444,12 @@ module Phaser {
} }
public set height(value: number) { public set height(value: number) {
if (value > this._game.stage.height)
{
value = this._game.stage.height;
}
this.worldView.height = value; this.worldView.height = value;
this.checkClip(); this.checkClip();
} }
+49
View File
@@ -0,0 +1,49 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Device {
constructor();
public desktop: bool;
public iOS: bool;
public android: bool;
public chromeOS: bool;
public linux: bool;
public macOS: bool;
public windows: bool;
public canvas: bool;
public file: bool;
public fileSystem: bool;
public localStorage: bool;
public webGL: bool;
public worker: bool;
public touch: bool;
public css3D: bool;
public arora: bool;
public chrome: bool;
public epiphany: bool;
public firefox: bool;
public ie: bool;
public ieVersion: number;
public mobileSafari: bool;
public midori: bool;
public opera: bool;
public safari: bool;
public webApp: bool;
public audioData: bool;
public webaudio: bool;
public ogg: bool;
public mp3: bool;
public wav: bool;
public m4a: bool;
public iPhone: bool;
public iPhone4: bool;
public iPad: bool;
public pixelRatio: number;
private _checkOS();
private _checkFeatures();
private _checkBrowser();
private _checkAudio();
private _checkDevice();
private _checkCSS3D();
public getAll(): string;
}
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class LinkedList {
constructor();
public object: Basic;
public next: LinkedList;
public destroy(): void;
}
}
+53
View File
@@ -0,0 +1,53 @@
/// <reference path="../Game.d.ts" />
/// <reference path="LinkedList.d.ts" />
module Phaser {
class QuadTree extends Rectangle {
constructor(X: number, Y: number, Width: number, Height: number, Parent?: QuadTree);
static A_LIST: number;
static B_LIST: number;
static divisions: number;
private _canSubdivide;
private _headA;
private _tailA;
private _headB;
private _tailB;
private static _min;
private _northWestTree;
private _northEastTree;
private _southEastTree;
private _southWestTree;
private _leftEdge;
private _rightEdge;
private _topEdge;
private _bottomEdge;
private _halfWidth;
private _halfHeight;
private _midpointX;
private _midpointY;
private static _object;
private static _objectLeftEdge;
private static _objectTopEdge;
private static _objectRightEdge;
private static _objectBottomEdge;
private static _list;
private static _useBothLists;
private static _processingCallback;
private static _notifyCallback;
private static _iterator;
private static _objectHullX;
private static _objectHullY;
private static _objectHullWidth;
private static _objectHullHeight;
private static _checkObjectHullX;
private static _checkObjectHullY;
private static _checkObjectHullWidth;
private static _checkObjectHullHeight;
public destroy(): void;
public load(ObjectOrGroup1: Basic, ObjectOrGroup2?: Basic, NotifyCallback?, ProcessCallback?): void;
public add(ObjectOrGroup: Basic, List: number): void;
private addObject();
private addToList();
public execute(): bool;
private overlapNode();
}
}
-2
View File
@@ -704,8 +704,6 @@ module Phaser {
*/ */
private overlapNode(): bool { private overlapNode(): bool {
//console.log('overlapNode');
//Walk the list and check for overlaps //Walk the list and check for overlaps
var overlapProcessed: bool = false; var overlapProcessed: bool = false;
var checkObject; var checkObject;
+26
View File
@@ -0,0 +1,26 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class RandomDataGenerator {
constructor(seeds?: string[]);
private s0;
private s1;
private s2;
private c;
private uint32();
private fract32();
private rnd();
private hash(data);
public sow(seeds?: string[]): void;
public integer : number;
public frac : number;
public real : number;
public integerInRange(min: number, max: number): number;
public realInRange(min: number, max: number): number;
public normal : number;
public uuid : string;
public pick(array);
public weightedPick(array);
public timestamp(min?: number, max?: number): number;
public angle : number;
}
}
+20
View File
@@ -0,0 +1,20 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class RequestAnimationFrame {
constructor(callback, callbackContext);
private _callback;
private _callbackContext;
public setCallback(callback): void;
private _timeOutID;
private _isSetTimeOut;
public isUsingSetTimeOut(): bool;
public isUsingRAF(): bool;
public lastTime: number;
public currentTime: number;
public isRunning: bool;
public start(callback?): void;
public stop(): void;
public RAFUpdate(): void;
public SetTimeoutUpdate(): void;
}
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../Game.d.ts" />
/// <reference path="../SoundManager.d.ts" />
module Phaser {
class Sound {
constructor(context, gainNode, data, volume?: number, loop?: bool);
private _context;
private _gainNode;
private _localGainNode;
private _buffer;
private _volume;
private _sound;
public loop: bool;
public duration: number;
public isPlaying: bool;
public isDecoding: bool;
public setDecodedBuffer(data): void;
public play(): void;
public stop(): void;
public mute(): void;
public unmute(): void;
public volume : number;
}
}
+1 -1
View File
@@ -54,7 +54,7 @@ module Phaser {
this._buffer = data; this._buffer = data;
this.isDecoding = false; this.isDecoding = false;
this.play(); //this.play();
} }
+21
View File
@@ -0,0 +1,21 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class StageScaleMode {
constructor(game: Game);
private _game;
private _startHeight;
private _iterations;
private _check;
static EXACT_FIT: number;
static NO_SCALE: number;
static SHOW_ALL: number;
public width: number;
public height: number;
public orientation;
public update(): void;
public isLandscape : bool;
private checkOrientation(event);
private refresh();
private setScreenSize();
}
}
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class Tile {
constructor(game: Game, tilemap: Tilemap, index: number, width: number, height: number);
private _game;
public name: string;
public mass: number;
public width: number;
public height: number;
public allowCollisions: number;
public collideLeft: bool;
public collideRight: bool;
public collideUp: bool;
public collideDown: bool;
public tilemap: Tilemap;
public index: number;
public destroy(): void;
public setCollision(collision: number, resetCollisions: bool): void;
public resetCollision(): void;
public toString(): string;
}
}
+90 -47
View File
@@ -3,55 +3,43 @@
/** /**
* Phaser - Tile * Phaser - Tile
* *
* A simple helper object for <code>Tilemap</code> that helps expand collision opportunities and control. * A Tile is a single representation of a tile within a Tilemap
*/ */
module Phaser { module Phaser {
export class Tile extends GameObject { export class Tile {
/** constructor(game: Game, tilemap: Tilemap, index: number, width: number, height: number) {
* Instantiate this new tile object. This is usually called from <code>Tilemap.loadMap()</code>.
*
* @param Tilemap A reference to the tilemap object creating the tile.
* @param Index The actual core map data index for this tile type.
* @param Width The width of the tile.
* @param Height The height of the tile.
* @param Visible Whether the tile is visible or not.
* @param AllowCollisions The collision flags for the object. By default this value is ANY or NONE depending on the parameters sent to loadMap().
*/
constructor(game: Game, Tilemap: Tilemap, Index: number, Width: number, Height: number, Visible: bool, AllowCollisions: number) {
super(game, 0, 0, Width, Height); this._game = game;
this.tilemap = tilemap;
this.index = index;
this.immovable = true; this.width = width;
this.moves = false; this.height = height;
this.callback = null; this.allowCollisions = Collision.NONE;
this.filter = null;
this.tilemap = Tilemap;
this.index = Index;
this.visible = Visible;
this.allowCollisions = AllowCollisions;
this.mapIndex = 0;
} }
/** private _game: Game;
* This function is called whenever an object hits a tile of this type.
* This function should take the form <code>myFunction(Tile:Tile,Object:Object)</code>.
* Defaults to null, set through <code>Tilemap.setTileProperties()</code>.
*/
public callback;
/** // You can give this Tile a friendly name to help with debugging. Never used internally.
* Each tile can store its own filter class for their callback functions. public name: string;
* That is, the callback will only be triggered if an object with a class
* type matching the filter touched it. public mass: number = 1.0;
* Defaults to null, set through <code>Tilemap.setTileProperties()</code>. public width: number;
*/ public height: number;
public filter;
public allowCollisions: number;
public collideLeft: bool = false;
public collideRight: bool = false;
public collideUp: bool = false;
public collideDown: bool = false;
public separateX: bool = true;
public separateY: bool = true;
/** /**
* A reference to the tilemap this tile object belongs to. * A reference to the tilemap this tile object belongs to.
@@ -65,24 +53,79 @@ module Phaser {
*/ */
public index: number; public index: number;
/**
* The current map index of this tile object at this moment.
* You can think of tile objects as moving around the tilemap helping with collisions.
* This value is only reliable and useful if used from the callback function.
*/
public mapIndex: number;
/** /**
* Clean up memory. * Clean up memory.
*/ */
public destroy() { public destroy() {
super.destroy();
this.callback = null;
this.tilemap = null; this.tilemap = null;
} }
public setCollision(collision: number, resetCollisions: bool, separateX: bool, separateY: bool) {
if (resetCollisions)
{
this.resetCollision();
}
this.separateX = separateX;
this.separateY = separateY;
this.allowCollisions = collision;
if (collision & Collision.ANY)
{
this.collideLeft = true;
this.collideRight = true;
this.collideUp = true;
this.collideDown = true;
return;
}
if (collision & Collision.LEFT || collision & Collision.WALL)
{
this.collideLeft = true;
}
if (collision & Collision.RIGHT || collision & Collision.WALL)
{
this.collideRight = true;
}
if (collision & Collision.UP || collision & Collision.CEILING)
{
this.collideUp = true;
}
if (collision & Collision.DOWN || collision & Collision.CEILING)
{
this.collideDown = true;
}
}
public resetCollision() {
this.allowCollisions = Collision.NONE;
this.collideLeft = false;
this.collideRight = false;
this.collideUp = false;
this.collideDown = false;
}
/**
* Returns a string representation of this object.
* @method toString
* @return {string} a string representation of the object.
**/
public toString(): string {
return "[{Tiled (index=" + this.index + " collisions=" + this.allowCollisions + " width=" + this.width + " height=" + this.height + ")}]";
}
} }
} }
-173
View File
@@ -1,173 +0,0 @@
/// <reference path="../Game.ts" />
/**
* Phaser - TilemapBuffer
*
* Responsible for rendering a portion of a tilemap to the given Camera.
*/
module Phaser {
export class TilemapBuffer {
constructor(game: Game, camera: Camera, tilemap: Tilemap, texture, tileOffsets) {
//console.log('New TilemapBuffer created for Camera ' + camera.ID);
this._game = game;
this.camera = camera;
this._tilemap = tilemap;
this._texture = texture;
this._tileOffsets = tileOffsets;
//this.createCanvas();
}
private _game: Game;
private _tilemap: Tilemap;
private _texture;
private _tileOffsets;
private _startX: number = 0;
private _maxX: number = 0;
private _startY: number = 0;
private _maxY: number = 0;
private _tx: number = 0;
private _ty: number = 0;
private _dx: number = 0;
private _dy: number = 0;
private _oldCameraX: number = 0;
private _oldCameraY: number = 0;
private _dirty: bool = true;
private _columnData;
public camera: Camera;
public canvas: HTMLCanvasElement;
public context: CanvasRenderingContext2D;
private createCanvas() {
this.canvas = <HTMLCanvasElement> document.createElement('canvas');
this.canvas.width = this._game.stage.width;
this.canvas.height = this._game.stage.height;
this.context = this.canvas.getContext('2d');
}
public update() {
/*
if (this.camera.worldView.x !== this._oldCameraX || this.camera.worldView.y !== this._oldCameraY)
{
this._dirty = true;
}
this._oldCameraX = this.camera.worldView.x;
this._oldCameraY = this.camera.worldView.y;
*/
}
public renderDebugInfo(x: number, y: number, color?: string = 'rgb(255,255,255)') {
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('TilemapBuffer', x, y);
this._game.stage.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14);
this._game.stage.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28);
this._game.stage.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42);
this._game.stage.context.fillText('Dirty: ' + this._dirty, x, y + 56);
}
public render(dx, dy): bool {
/*
if (this._dirty == false)
{
this._game.stage.context.drawImage(this.canvas, 0, 0);
return true;
}
*/
// Work out how many tiles we can fit into our camera and round it up for the edges
this._maxX = this._game.math.ceil(this.camera.width / this._tilemap.tileWidth) + 1;
this._maxY = this._game.math.ceil(this.camera.height / this._tilemap.tileHeight) + 1;
// And now work out where in the tilemap the camera actually is
this._startX = this._game.math.floor(this.camera.worldView.x / this._tilemap.tileWidth);
this._startY = this._game.math.floor(this.camera.worldView.y / this._tilemap.tileHeight);
// Tilemap bounds check
if (this._startX < 0)
{
this._startX = 0;
}
if (this._startY < 0)
{
this._startY = 0;
}
if (this._startX + this._maxX > this._tilemap.widthInTiles)
{
this._startX = this._tilemap.widthInTiles - this._maxX;
}
if (this._startY + this._maxY > this._tilemap.heightInTiles)
{
this._startY = this._tilemap.heightInTiles - this._maxY;
}
// Finally get the offset to avoid the blocky movement
this._dx = dx;
this._dy = dy;
this._dx += -(this.camera.worldView.x - (this._startX * this._tilemap.tileWidth));
this._dy += -(this.camera.worldView.y - (this._startY * this._tilemap.tileHeight));
this._tx = this._dx;
this._ty = this._dy;
for (var row = this._startY; row < this._startY + this._maxY; row++)
{
this._columnData = this._tilemap.mapData[row];
for (var tile = this._startX; tile < this._startX + this._maxX; tile++)
{
if (this._tileOffsets[this._columnData[tile]])
{
//this.context.drawImage(
this._game.stage.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._tilemap.tileWidth, // Source Width
this._tilemap.tileHeight, // Source Height
this._tx, // Destination X (where on the canvas it'll be drawn)
this._ty, // Destination Y
this._tilemap.tileWidth, // Destination Width (always same as Source Width unless scaled)
this._tilemap.tileHeight // Destination Height (always same as Source Height unless scaled)
);
this._tx += this._tilemap.tileWidth;
}
}
this._tx = this._dx;
this._ty += this._tilemap.tileHeight;
}
//this._game.stage.context.drawImage(this.canvas, 0, 0);
//console.log('dirty cleaned');
//this._dirty = false;
return true;
}
}
}
+51
View File
@@ -0,0 +1,51 @@
/// <reference path="../Game.d.ts" />
module Phaser {
class TilemapLayer {
constructor(game: Game, parent: Tilemap, key: string, mapFormat: number, name: string, tileWidth: number, tileHeight: number);
private _game;
private _parent;
private _texture;
private _tileOffsets;
private _startX;
private _startY;
private _maxX;
private _maxY;
private _tx;
private _ty;
private _dx;
private _dy;
private _oldCameraX;
private _oldCameraY;
private _columnData;
private _tempTileX;
private _tempTileY;
private _tempTileW;
private _tempTileH;
public name: string;
public alpha: number;
public exists: bool;
public visible: bool;
public orientation: string;
public properties: {};
public mapData;
public mapFormat: number;
public boundsInTiles: Rectangle;
public tileWidth: number;
public tileHeight: number;
public widthInTiles: number;
public heightInTiles: number;
public widthInPixels: number;
public heightInPixels: number;
public tileMargin: number;
public tileSpacing: number;
public getTileFromWorldXY(x: number, y: number): number;
public getTileOverlaps(object: GameObject): bool;
public getTileBlock(x: number, y: number, width: number, height: number): any[];
public getTileIndex(x: number, y: number): number;
public addColumn(column): void;
public updateBounds(): void;
public parseTileOffsets(): number;
public renderDebugInfo(x: number, y: number, color?: string): void;
public render(camera: Camera, dx, dy): bool;
}
}
+456
View File
@@ -0,0 +1,456 @@
/// <reference path="../Game.ts" />
/**
* Phaser - TilemapLayer
*
* A Tilemap Layer. Tiled format maps can have multiple overlapping layers.
*/
module Phaser {
export class TilemapLayer {
constructor(game: Game, parent:Tilemap, key: string, mapFormat: number, name: string, tileWidth: number, tileHeight: number) {
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.mapData = [];
this._tempTileBlock = [];
this._texture = this._game.cache.getImage(key);
}
private _game: Game;
private _parent: Tilemap;
private _texture;
private _tileOffsets;
private _startX: number = 0;
private _startY: number = 0;
private _maxX: number = 0;
private _maxY: number = 0;
private _tx: number = 0;
private _ty: number = 0;
private _dx: number = 0;
private _dy: number = 0;
private _oldCameraX: number = 0;
private _oldCameraY: number = 0;
private _columnData;
private _tempTileX: number;
private _tempTileY: number;
private _tempTileW: number;
private _tempTileH: number;
private _tempTileBlock;
private _tempBlockResults;
public name: string;
public alpha: number = 1;
public exists: bool = true;
public visible: bool = true;
//public scrollFactor: MicroPoint;
public orientation: string;
public properties: {};
public mapData;
public mapFormat: number;
public boundsInTiles: Rectangle;
public tileWidth: number;
public tileHeight: number;
public widthInTiles: number = 0;
public heightInTiles: number = 0;
public widthInPixels: number = 0;
public heightInPixels: number = 0;
public tileMargin: number = 0;
public tileSpacing: number = 0;
public putTile(x: number, y: number, index: number) {
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;
}
}
}
public swapTile(tileA: number, tileB: number, x?: number = 0, y?: number = 0, width?: number = this.widthInTiles, height?: number = 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;
}
}
}
public fillTile(index: number, x?: number = 0, y?: number = 0, width?: number = this.widthInTiles, height?: number = 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;
}
}
public randomiseTiles(tiles: number[], x?: number = 0, y?: number = 0, width?: number = this.widthInTiles, height?: number = 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);
}
}
public replaceTile(tileA: number, tileB: number, x?: number = 0, y?: number = 0, width?: number = this.widthInTiles, height?: number = 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;
}
}
}
public getTileBlock(x: number, y: number, width: number, height: number) {
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;
}
public getTileFromWorldXY(x: number, y: number): number {
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);
}
public getTileOverlaps(object: GameObject) {
// If the object is outside of the world coordinates then abort the check (tilemap has to exist within world bounds)
if (object.bounds.x < 0 || object.bounds.x > this.widthInPixels || object.bounds.y < 0 || object.bounds.bottom > this.heightInPixels)
{
return;
}
// What tiles do we need to check against?
this._tempTileX = this._game.math.snapToFloor(object.bounds.x, this.tileWidth) / this.tileWidth;
this._tempTileY = this._game.math.snapToFloor(object.bounds.y, this.tileHeight) / this.tileHeight;
this._tempTileW = (this._game.math.snapToCeil(object.bounds.width, this.tileWidth) + this.tileWidth) / this.tileWidth;
this._tempTileH = (this._game.math.snapToCeil(object.bounds.height, this.tileHeight) + this.tileHeight) / this.tileHeight;
// Loop through the tiles we've got and check overlaps accordingly (the results are stored in this._tempTileBlock)
this._tempBlockResults = [];
this.getTempBlock(this._tempTileX, this._tempTileY, this._tempTileW, this._tempTileH, true);
Collision.TILE_OVERLAP = false;
for (var r = 0; r < this._tempTileBlock.length; r++)
{
if (Collision.separateTile(object, this._tempTileBlock[r].x * this.tileWidth, this._tempTileBlock[r].y * this.tileHeight, this.tileWidth, this.tileHeight, this._tempTileBlock[r].tile.mass, this._tempTileBlock[r].tile.collideLeft, this._tempTileBlock[r].tile.collideRight, this._tempTileBlock[r].tile.collideUp, this._tempTileBlock[r].tile.collideDown, this._tempTileBlock[r].tile.separateX, this._tempTileBlock[r].tile.separateY) == true)
{
this._tempBlockResults.push({ x: this._tempTileBlock[r].x, y: this._tempTileBlock[r].y, tile: this._tempTileBlock[r].tile });
}
}
return this._tempBlockResults;
}
private getTempBlock(x: number, y: number, width: number, height: number, collisionOnly?: bool = false) {
if (x < 0)
{
x = 0;
}
if (y < 0)
{
y = 0;
}
if (width > this.widthInTiles)
{
width = this.widthInTiles;
}
if (height > this.heightInTiles)
{
height = this.heightInTiles;
}
this._tempTileBlock = [];
for (var ty = y; ty < y + height; ty++)
{
for (var tx = x; tx < x + width; tx++)
{
if (collisionOnly)
{
// We only want to consider the tile for checking if you can actually collide with it
if (this.mapData[ty] && this.mapData[ty][tx] && this._parent.tiles[this.mapData[ty][tx]].allowCollisions != Collision.NONE)
{
this._tempTileBlock.push({ x: tx, y: ty, tile: this._parent.tiles[this.mapData[ty][tx]] });
}
}
else
{
if (this.mapData[ty] && this.mapData[ty][tx])
{
this._tempTileBlock.push({ x: tx, y: ty, tile: this._parent.tiles[this.mapData[ty][tx]] });
}
}
}
}
}
public getTileIndex(x: number, y: number): number {
if (y >= 0 && y < this.mapData.length)
{
if (x >= 0 && x < this.mapData[y].length)
{
return this.mapData[y][x];
}
}
return null;
}
public addColumn(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;
}
public updateBounds() {
this.boundsInTiles.setTo(0, 0, this.widthInTiles, this.heightInTiles);
}
public parseTileOffsets():number {
this._tileOffsets = [];
var i = 0;
if (this.mapFormat == Tilemap.FORMAT_TILED_JSON)
{
// For some reason Tiled counts from 1 not 0
this._tileOffsets[0] = null;
i = 1;
}
for (var ty = this.tileMargin; ty < this._texture.height; ty += (this.tileHeight + this.tileSpacing))
{
for (var tx = this.tileMargin; tx < this._texture.width; tx += (this.tileWidth + this.tileSpacing))
{
this._tileOffsets[i] = { x: tx, y: ty };
i++;
}
}
return this._tileOffsets.length;
}
public renderDebugInfo(x: number, y: number, color?: string = 'rgb(255,255,255)') {
this._game.stage.context.fillStyle = color;
this._game.stage.context.fillText('TilemapLayer: ' + this.name, x, y);
this._game.stage.context.fillText('startX: ' + this._startX + ' endX: ' + this._maxX, x, y + 14);
this._game.stage.context.fillText('startY: ' + this._startY + ' endY: ' + this._maxY, x, y + 28);
this._game.stage.context.fillText('dx: ' + this._dx + ' dy: ' + this._dy, x, y + 42);
}
public render(camera: Camera, dx, dy): bool {
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._game.stage.context.globalAlpha;
this._game.stage.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._game.stage.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._game.stage.context.globalAlpha = globalAlpha;
}
return true;
}
}
}
+42
View File
@@ -0,0 +1,42 @@
/// <reference path="../Game.d.ts" />
/// <reference path="easing/Back.d.ts" />
/// <reference path="easing/Bounce.d.ts" />
/// <reference path="easing/Circular.d.ts" />
/// <reference path="easing/Cubic.d.ts" />
/// <reference path="easing/Elastic.d.ts" />
/// <reference path="easing/Exponential.d.ts" />
/// <reference path="easing/Linear.d.ts" />
/// <reference path="easing/Quadratic.d.ts" />
/// <reference path="easing/Quartic.d.ts" />
/// <reference path="easing/Quintic.d.ts" />
/// <reference path="easing/Sinusoidal.d.ts" />
module Phaser {
class Tween {
constructor(object, game: Game);
private _game;
private _manager;
private _object;
private _pausedTime;
private _valuesStart;
private _valuesEnd;
private _duration;
private _delayTime;
private _startTime;
private _easingFunction;
private _interpolationFunction;
private _chainedTweens;
public onStart: Signal;
public onUpdate: Signal;
public onComplete: Signal;
public to(properties, duration?: number, ease?: any, autoStart?: bool): Tween;
public start(): Tween;
public stop(): Tween;
public parent : Game;
public delay : number;
public easing : any;
public interpolation : any;
public chain(tween: Tween): Tween;
public debugValue;
public update(time): bool;
}
}
+3
View File
@@ -30,6 +30,7 @@ module Phaser {
this._interpolationFunction = this._game.math.linearInterpolation; this._interpolationFunction = this._game.math.linearInterpolation;
this._easingFunction = Phaser.Easing.Linear.None; this._easingFunction = Phaser.Easing.Linear.None;
this._chainedTweens = [];
this.onStart = new Phaser.Signal(); this.onStart = new Phaser.Signal();
this.onUpdate = new Phaser.Signal(); this.onUpdate = new Phaser.Signal();
this.onComplete = new Phaser.Signal(); this.onComplete = new Phaser.Signal();
@@ -126,6 +127,8 @@ module Phaser {
this._manager.remove(this); this._manager.remove(this);
} }
this.onComplete.dispose();
return this; return this;
} }
+27
View File
@@ -0,0 +1,27 @@
/// <reference path="../../Game.d.ts" />
module Phaser {
class Animation {
constructor(game: Game, parent: Sprite, frameData: FrameData, name: string, frames, delay: number, looped: bool);
private _game;
private _parent;
private _frames;
private _frameData;
private _frameIndex;
private _timeLastFrame;
private _timeNextFrame;
public name: string;
public currentFrame: Frame;
public isFinished: bool;
public isPlaying: bool;
public looped: bool;
public delay: number;
public frameTotal : number;
public frame : number;
public play(frameRate?: number, loop?: bool): void;
public restart(): void;
public stop(): void;
public update(): bool;
public destroy(): void;
private onComplete();
}
}
+20 -4
View File
@@ -24,6 +24,9 @@ module Phaser {
this.isFinished = false; this.isFinished = false;
this.isPlaying = false; this.isPlaying = false;
this._frameIndex = 0;
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
} }
private _game: Game; private _game: Game;
@@ -87,11 +90,16 @@ module Phaser {
} }
private onComplete() { public restart() {
this.isPlaying = false; this.isPlaying = true;
this.isFinished = true; this.isFinished = false;
// callback
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]);
} }
@@ -146,6 +154,14 @@ module Phaser {
} }
private onComplete() {
this.isPlaying = false;
this.isFinished = true;
// callback
}
} }
} }
+7
View File
@@ -0,0 +1,7 @@
/// <reference path="../../Game.d.ts" />
module Phaser {
class AnimationLoader {
static parseSpriteSheet(game: Game, key: string, frameWidth: number, frameHeight: number, frameMax: number): FrameData;
static parseJSONData(game: Game, json): FrameData;
}
}
+23
View File
@@ -0,0 +1,23 @@
/// <reference path="../../Game.d.ts" />
module Phaser {
class Frame {
constructor(x: number, y: number, width: number, height: number, name: string);
public x: number;
public y: number;
public width: number;
public height: number;
public index: number;
public name: string;
public rotated: bool;
public rotationDirection: string;
public trimmed: bool;
public sourceSizeW: number;
public sourceSizeH: number;
public spriteSourceSizeX: number;
public spriteSourceSizeY: number;
public spriteSourceSizeW: number;
public spriteSourceSizeH: number;
public setRotation(rotated: bool, rotationDirection: string): void;
public setTrim(trimmed: bool, actualWidth, actualHeight, destX, destY, destWidth, destHeight): void;
}
}
+18
View File
@@ -0,0 +1,18 @@
/// <reference path="../../Game.d.ts" />
module Phaser {
class FrameData {
constructor();
private _frames;
private _frameNames;
public total : number;
public addFrame(frame: Frame): Frame;
public getFrame(index: number): Frame;
public getFrameByName(name: string): Frame;
public checkFrameName(name: string): bool;
public getFrameRange(start: number, end: number, output?: Frame[]): Frame[];
public getFrameIndexes(output?: number[]): number[];
public getFrameIndexesByName(input: string[]): number[];
public getAllFrames(): Frame[];
public getFrames(range: number[]): Frame[];
}
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../../Game.d.ts" />
module Phaser.Easing {
class Back {
static In(k): number;
static Out(k): number;
static InOut(k): number;
}
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../../Game.d.ts" />
module Phaser.Easing {
class Bounce {
static In(k): number;
static Out(k): number;
static InOut(k): number;
}
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../../Game.d.ts" />
module Phaser.Easing {
class Circular {
static In(k): number;
static Out(k): number;
static InOut(k): number;
}
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../../Game.d.ts" />
module Phaser.Easing {
class Cubic {
static In(k): number;
static Out(k): number;
static InOut(k): number;
}
}
+8
View File
@@ -0,0 +1,8 @@
/// <reference path="../../Game.d.ts" />
module Phaser.Easing {
class Elastic {
static In(k): number;
static Out(k): number;
static InOut(k): number;
}
}

Some files were not shown because too many files have changed in this diff Show More