Added phaser build and hellophaser sample
This commit is contained in:
9
src/Intro.js
Normal file
9
src/Intro.js
Normal file
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
(function(){
|
||||
|
||||
var root = this;
|
||||
21
src/Outro.js
Normal file
21
src/Outro.js
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
if (typeof exports !== 'undefined') {
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
exports = module.exports = Phaser;
|
||||
}
|
||||
exports.Phaser = Phaser;
|
||||
} else if (typeof define !== 'undefined' && define.amd) {
|
||||
define('Phaser', (function() { return root.Phaser = Phaser; }) ());
|
||||
} else {
|
||||
root.Phaser = Phaser;
|
||||
}
|
||||
}).call(this);
|
||||
|
||||
/*
|
||||
* "Don't follow strange women who lure you into woods with beautiful poetry." - @djfood
|
||||
*/
|
||||
81
src/Phaser.js
Normal file
81
src/Phaser.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/* global Phaser:true */
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @namespace Phaser
|
||||
*/
|
||||
var Phaser = Phaser || {
|
||||
|
||||
VERSION: '2.0.5',
|
||||
GAMES: [],
|
||||
|
||||
AUTO: 0,
|
||||
CANVAS: 1,
|
||||
WEBGL: 2,
|
||||
HEADLESS: 3,
|
||||
|
||||
NONE: 0,
|
||||
LEFT: 1,
|
||||
RIGHT: 2,
|
||||
UP: 3,
|
||||
DOWN: 4,
|
||||
|
||||
SPRITE: 0,
|
||||
BUTTON: 1,
|
||||
IMAGE: 2,
|
||||
GRAPHICS: 3,
|
||||
TEXT: 4,
|
||||
TILESPRITE: 5,
|
||||
BITMAPTEXT: 6,
|
||||
GROUP: 7,
|
||||
RENDERTEXTURE: 8,
|
||||
TILEMAP: 9,
|
||||
TILEMAPLAYER: 10,
|
||||
EMITTER: 11,
|
||||
POLYGON: 12,
|
||||
BITMAPDATA: 13,
|
||||
CANVAS_FILTER: 14,
|
||||
WEBGL_FILTER: 15,
|
||||
ELLIPSE: 16,
|
||||
SPRITEBATCH: 17,
|
||||
RETROFONT: 18,
|
||||
POINTER: 19,
|
||||
|
||||
// The various blend modes supported by pixi / phaser
|
||||
blendModes: {
|
||||
NORMAL:0,
|
||||
ADD:1,
|
||||
MULTIPLY:2,
|
||||
SCREEN:3,
|
||||
OVERLAY:4,
|
||||
DARKEN:5,
|
||||
LIGHTEN:6,
|
||||
COLOR_DODGE:7,
|
||||
COLOR_BURN:8,
|
||||
HARD_LIGHT:9,
|
||||
SOFT_LIGHT:10,
|
||||
DIFFERENCE:11,
|
||||
EXCLUSION:12,
|
||||
HUE:13,
|
||||
SATURATION:14,
|
||||
COLOR:15,
|
||||
LUMINOSITY:16
|
||||
},
|
||||
|
||||
// The scale modes
|
||||
scaleModes: {
|
||||
DEFAULT:0,
|
||||
LINEAR:0,
|
||||
NEAREST:1
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// We don't need this in Pixi, so we've removed it to save space
|
||||
// however the Stage object expects a reference to it, so here is a dummy entry.
|
||||
// Ensure that an existing PIXI.InteractionManager is not overriden - in case you're using your own PIXI library.
|
||||
PIXI.InteractionManager = PIXI.InteractionManager || function () {};
|
||||
639
src/animation/Animation.js
Normal file
639
src/animation/Animation.js
Normal file
@@ -0,0 +1,639 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* An Animation instance contains a single animation and the controls to play it.
|
||||
* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
|
||||
*
|
||||
* @class Phaser.Animation
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
|
||||
* @param {string} name - The unique name for this animation, used in playback commands.
|
||||
* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
|
||||
* @param {(Array.<number>|Array.<string>)} frames - An array of numbers or strings indicating which frames to play in which order.
|
||||
* @param {number} delay - The time between each frame of the animation, given in ms.
|
||||
* @param {boolean} loop - Should this animation loop when it reaches the end or play through once.
|
||||
*/
|
||||
Phaser.Animation = function (game, parent, name, frameData, frames, delay, loop) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
|
||||
* @private
|
||||
*/
|
||||
this._parent = parent;
|
||||
|
||||
/**
|
||||
* @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
|
||||
* @private
|
||||
*/
|
||||
this._frameData = frameData;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this Animation.
|
||||
*/
|
||||
this.name = name;
|
||||
|
||||
/**
|
||||
* @property {array} _frames
|
||||
* @private
|
||||
*/
|
||||
this._frames = [];
|
||||
this._frames = this._frames.concat(frames);
|
||||
|
||||
/**
|
||||
* @property {number} delay - The delay in ms between each frame of the Animation.
|
||||
*/
|
||||
this.delay = 1000 / delay;
|
||||
|
||||
/**
|
||||
* @property {boolean} loop - The loop state of the Animation.
|
||||
*/
|
||||
this.loop = loop;
|
||||
|
||||
/**
|
||||
* @property {number} loopCount - The number of times the animation has looped since it was last started.
|
||||
*/
|
||||
this.loopCount = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
|
||||
* @default
|
||||
*/
|
||||
this.killOnComplete = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
|
||||
* @default
|
||||
*/
|
||||
this.isFinished = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
|
||||
* @default
|
||||
*/
|
||||
this.isPlaying = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isPaused - The paused state of the Animation.
|
||||
* @default
|
||||
*/
|
||||
this.isPaused = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} _pauseStartTime - The time the animation paused.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._pauseStartTime = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _frameIndex
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._frameIndex = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _frameDiff
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._frameDiff = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _frameSkip
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._frameSkip = 1;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
|
||||
*/
|
||||
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
|
||||
*/
|
||||
this.onStart = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onAnimationLoop instead.
|
||||
*/
|
||||
this.onComplete = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
|
||||
*/
|
||||
this.onLoop = new Phaser.Signal();
|
||||
|
||||
// Set-up some event listeners
|
||||
this.game.onPause.add(this.onPause, this);
|
||||
this.game.onResume.add(this.onResume, this);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Animation.prototype = {
|
||||
|
||||
/**
|
||||
* Plays this animation.
|
||||
*
|
||||
* @method Phaser.Animation#play
|
||||
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
|
||||
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
|
||||
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
|
||||
* @return {Phaser.Animation} - A reference to this Animation instance.
|
||||
*/
|
||||
play: function (frameRate, loop, killOnComplete) {
|
||||
|
||||
if (typeof frameRate === 'number')
|
||||
{
|
||||
// If they set a new frame rate then use it, otherwise use the one set on creation
|
||||
this.delay = 1000 / frameRate;
|
||||
}
|
||||
|
||||
if (typeof loop === 'boolean')
|
||||
{
|
||||
// If they set a new loop value then use it, otherwise use the one set on creation
|
||||
this.loop = loop;
|
||||
}
|
||||
|
||||
if (typeof killOnComplete !== 'undefined')
|
||||
{
|
||||
// Remove the parent sprite once the animation has finished?
|
||||
this.killOnComplete = killOnComplete;
|
||||
}
|
||||
|
||||
this.isPlaying = true;
|
||||
this.isFinished = false;
|
||||
this.paused = false;
|
||||
this.loopCount = 0;
|
||||
|
||||
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]);
|
||||
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
// TODO: Double check if required
|
||||
if (this._parent.__tilePattern)
|
||||
{
|
||||
this._parent.__tilePattern = false;
|
||||
this._parent.tilingTexture = false;
|
||||
}
|
||||
|
||||
this._parent.events.onAnimationStart.dispatch(this._parent, this);
|
||||
this.onStart.dispatch(this._parent, this);
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets this animation back to the first frame and restarts the animation.
|
||||
*
|
||||
* @method Phaser.Animation#restart
|
||||
*/
|
||||
restart: function () {
|
||||
|
||||
this.isPlaying = true;
|
||||
this.isFinished = false;
|
||||
this.paused = false;
|
||||
this.loopCount = 0;
|
||||
|
||||
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]);
|
||||
|
||||
this.onStart.dispatch(this._parent, this);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets this animations playback to a given frame with the given ID.
|
||||
*
|
||||
* @method Phaser.Animation#setFrame
|
||||
* @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index.
|
||||
* @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation.
|
||||
*/
|
||||
setFrame: function(frameId, useLocalFrameIndex) {
|
||||
|
||||
var frameIndex;
|
||||
|
||||
if (typeof useLocalFrameIndex === 'undefined')
|
||||
{
|
||||
useLocalFrameIndex = false;
|
||||
}
|
||||
|
||||
// Find the index to the desired frame.
|
||||
if (typeof frameId === "string")
|
||||
{
|
||||
for (var i = 0; i < this._frames.length; i++)
|
||||
{
|
||||
if (this._frameData.getFrame(this._frames[i]).name === frameId)
|
||||
{
|
||||
frameIndex = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (typeof frameId === "number")
|
||||
{
|
||||
if (useLocalFrameIndex)
|
||||
{
|
||||
frameIndex = frameId;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = 0; i < this._frames.length; i++)
|
||||
{
|
||||
if (this.frames[i] === frameIndex)
|
||||
{
|
||||
frameIndex = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (frameIndex)
|
||||
{
|
||||
// Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
|
||||
this._frameIndex = frameIndex - 1;
|
||||
|
||||
// Make the animation update at next update
|
||||
this._timeNextFrame = this.game.time.now;
|
||||
|
||||
this.update();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
|
||||
* If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
|
||||
*
|
||||
* @method Phaser.Animation#stop
|
||||
* @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
|
||||
* @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
|
||||
*/
|
||||
stop: function (resetFrame, dispatchComplete) {
|
||||
|
||||
if (typeof resetFrame === 'undefined') { resetFrame = false; }
|
||||
if (typeof dispatchComplete === 'undefined') { dispatchComplete = false; }
|
||||
|
||||
this.isPlaying = false;
|
||||
this.isFinished = true;
|
||||
this.paused = false;
|
||||
|
||||
if (resetFrame)
|
||||
{
|
||||
this.currentFrame = this._frameData.getFrame(this._frames[0]);
|
||||
}
|
||||
|
||||
if (dispatchComplete)
|
||||
{
|
||||
this._parent.events.onAnimationComplete.dispatch(this._parent, this);
|
||||
this.onComplete.dispatch(this._parent, this);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the Game enters a paused state.
|
||||
*
|
||||
* @method Phaser.Animation#onPause
|
||||
*/
|
||||
onPause: function () {
|
||||
|
||||
if (this.isPlaying)
|
||||
{
|
||||
this._frameDiff = this._timeNextFrame - this.game.time.now;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the Game resumes from a paused state.
|
||||
*
|
||||
* @method Phaser.Animation#onResume
|
||||
*/
|
||||
onResume: function () {
|
||||
|
||||
if (this.isPlaying)
|
||||
{
|
||||
this._timeNextFrame = this.game.time.now + this._frameDiff;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates this animation. Called automatically by the AnimationManager.
|
||||
*
|
||||
* @method Phaser.Animation#update
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
if (this.isPaused)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.isPlaying === true && this.game.time.now >= this._timeNextFrame)
|
||||
{
|
||||
this._frameSkip = 1;
|
||||
|
||||
// Lagging?
|
||||
this._frameDiff = this.game.time.now - this._timeNextFrame;
|
||||
|
||||
this._timeLastFrame = this.game.time.now;
|
||||
|
||||
if (this._frameDiff > this.delay)
|
||||
{
|
||||
// We need to skip a frame, work out how many
|
||||
this._frameSkip = Math.floor(this._frameDiff / this.delay);
|
||||
|
||||
this._frameDiff -= (this._frameSkip * this.delay);
|
||||
}
|
||||
|
||||
// And what's left now?
|
||||
this._timeNextFrame = this.game.time.now + (this.delay - this._frameDiff);
|
||||
|
||||
this._frameIndex += this._frameSkip;
|
||||
|
||||
if (this._frameIndex >= this._frames.length)
|
||||
{
|
||||
if (this.loop)
|
||||
{
|
||||
this._frameIndex %= this._frames.length;
|
||||
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this._parent.__tilePattern)
|
||||
{
|
||||
this._parent.__tilePattern = false;
|
||||
this._parent.tilingTexture = false;
|
||||
}
|
||||
}
|
||||
|
||||
this.loopCount++;
|
||||
this._parent.events.onAnimationLoop.dispatch(this._parent, this);
|
||||
this.onLoop.dispatch(this._parent, this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.complete();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this._parent.__tilePattern)
|
||||
{
|
||||
this._parent.__tilePattern = false;
|
||||
this._parent.tilingTexture = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Cleans up this animation ready for deletion. Nulls all values and references.
|
||||
*
|
||||
* @method Phaser.Animation#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
this.game.onPause.remove(this.onPause, this);
|
||||
this.game.onResume.remove(this.onResume, this);
|
||||
|
||||
this.game = null;
|
||||
this._parent = null;
|
||||
this._frames = null;
|
||||
this._frameData = null;
|
||||
this.currentFrame = null;
|
||||
this.isPlaying = false;
|
||||
|
||||
this.onStart.dispose();
|
||||
this.onLoop.dispose();
|
||||
this.onComplete.dispose();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called internally when the animation finishes playback.
|
||||
* Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
|
||||
*
|
||||
* @method Phaser.Animation#complete
|
||||
*/
|
||||
complete: function () {
|
||||
|
||||
this.isPlaying = false;
|
||||
this.isFinished = true;
|
||||
this.paused = false;
|
||||
|
||||
this._parent.events.onAnimationComplete.dispatch(this._parent, this);
|
||||
|
||||
this.onComplete.dispatch(this._parent, this);
|
||||
|
||||
if (this.killOnComplete)
|
||||
{
|
||||
this._parent.kill();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Animation.prototype.constructor = Phaser.Animation;
|
||||
|
||||
/**
|
||||
* @name Phaser.Animation#paused
|
||||
* @property {boolean} paused - Gets and sets the paused state of this Animation.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Animation.prototype, 'paused', {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.isPaused;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.isPaused = value;
|
||||
|
||||
if (value)
|
||||
{
|
||||
// Paused
|
||||
this._pauseStartTime = this.game.time.now;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Un-paused
|
||||
if (this.isPlaying)
|
||||
{
|
||||
this._timeNextFrame = this.game.time.now + this.delay;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Animation#frameTotal
|
||||
* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
|
||||
|
||||
get: function () {
|
||||
return this._frames.length;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Animation#frame
|
||||
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Animation.prototype, 'frame', {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.currentFrame !== null)
|
||||
{
|
||||
return this.currentFrame.index;
|
||||
}
|
||||
else
|
||||
{
|
||||
return this._frameIndex;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.currentFrame = this._frameData.getFrame(this._frames[value]);
|
||||
|
||||
if (this.currentFrame !== null)
|
||||
{
|
||||
this._frameIndex = value;
|
||||
this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Animation#speed
|
||||
* @property {number} speed - Gets or sets the current speed of the animation, the time between each frame of the animation, given in ms. Takes effect from the NEXT frame. Minimum value is 1.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Animation.prototype, 'speed', {
|
||||
|
||||
get: function () {
|
||||
|
||||
return Math.round(1000 / this.delay);
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value >= 1)
|
||||
{
|
||||
this.delay = 1000 / value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
|
||||
* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
|
||||
* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
|
||||
*
|
||||
* @method Phaser.Animation.generateFrameNames
|
||||
* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
|
||||
* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
|
||||
* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
|
||||
* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
|
||||
* @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
|
||||
* @return {array} An array of framenames.
|
||||
*/
|
||||
Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
|
||||
|
||||
if (typeof suffix == 'undefined') { suffix = ''; }
|
||||
|
||||
var output = [];
|
||||
var frame = '';
|
||||
|
||||
if (start < stop)
|
||||
{
|
||||
for (var i = start; i <= stop; i++)
|
||||
{
|
||||
if (typeof zeroPad == 'number')
|
||||
{
|
||||
// str, len, pad, dir
|
||||
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
frame = i.toString();
|
||||
}
|
||||
|
||||
frame = prefix + frame + suffix;
|
||||
|
||||
output.push(frame);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var i = start; i >= stop; i--)
|
||||
{
|
||||
if (typeof zeroPad == 'number')
|
||||
{
|
||||
// str, len, pad, dir
|
||||
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
frame = i.toString();
|
||||
}
|
||||
|
||||
frame = prefix + frame + suffix;
|
||||
|
||||
output.push(frame);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
};
|
||||
480
src/animation/AnimationManager.js
Normal file
480
src/animation/AnimationManager.js
Normal file
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Animation Manager is used to add, play and update Phaser Animations.
|
||||
* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
|
||||
*
|
||||
* @class Phaser.AnimationManager
|
||||
* @constructor
|
||||
* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
|
||||
*/
|
||||
Phaser.AnimationManager = function (sprite) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
|
||||
*/
|
||||
this.sprite = sprite;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = sprite.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Frame} currentFrame - The currently displayed Frame of animation, if any.
|
||||
* @default
|
||||
*/
|
||||
this.currentFrame = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Animation} currentAnim - The currently displayed animation, if any.
|
||||
* @default
|
||||
*/
|
||||
this.currentAnim = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
|
||||
* @default
|
||||
*/
|
||||
this.updateIfVisible = true;
|
||||
|
||||
/**
|
||||
* @property {boolean} isLoaded - Set to true once animation data has been loaded.
|
||||
* @default
|
||||
*/
|
||||
this.isLoaded = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._frameData = null;
|
||||
|
||||
/**
|
||||
* @property {object} _anims - An internal object that stores all of the Animation instances.
|
||||
* @private
|
||||
*/
|
||||
this._anims = {};
|
||||
|
||||
/**
|
||||
* @property {object} _outputFrames - An internal object to help avoid gc.
|
||||
* @private
|
||||
*/
|
||||
this._outputFrames = [];
|
||||
|
||||
};
|
||||
|
||||
Phaser.AnimationManager.prototype = {
|
||||
|
||||
/**
|
||||
* Loads FrameData into the internal temporary vars and resets the frame index to zero.
|
||||
* This is called automatically when a new Sprite is created.
|
||||
*
|
||||
* @method Phaser.AnimationManager#loadFrameData
|
||||
* @private
|
||||
* @param {Phaser.FrameData} frameData - The FrameData set to load.
|
||||
*/
|
||||
loadFrameData: function (frameData) {
|
||||
|
||||
this._frameData = frameData;
|
||||
this.frame = 0;
|
||||
this.isLoaded = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
|
||||
* Animations added in this way are played back with the play function.
|
||||
*
|
||||
* @method Phaser.AnimationManager#add
|
||||
* @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
|
||||
* @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
|
||||
* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
|
||||
* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
|
||||
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
|
||||
* @return {Phaser.Animation} The Animation object that was created.
|
||||
*/
|
||||
add: function (name, frames, frameRate, loop, useNumericIndex) {
|
||||
|
||||
if (this._frameData === null)
|
||||
{
|
||||
console.warn('No FrameData available for Phaser.Animation ' + name);
|
||||
return;
|
||||
}
|
||||
|
||||
frames = frames || [];
|
||||
frameRate = frameRate || 60;
|
||||
|
||||
if (typeof loop === 'undefined') { loop = false; }
|
||||
|
||||
// If they didn't set the useNumericIndex then let's at least try and guess it
|
||||
if (typeof useNumericIndex === 'undefined')
|
||||
{
|
||||
if (frames && typeof frames[0] === 'number')
|
||||
{
|
||||
useNumericIndex = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
useNumericIndex = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Create the signals the AnimationManager will emit
|
||||
if (this.sprite.events.onAnimationStart === null)
|
||||
{
|
||||
this.sprite.events.onAnimationStart = new Phaser.Signal();
|
||||
this.sprite.events.onAnimationComplete = new Phaser.Signal();
|
||||
this.sprite.events.onAnimationLoop = new Phaser.Signal();
|
||||
}
|
||||
|
||||
this._outputFrames.length = 0;
|
||||
|
||||
this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
|
||||
|
||||
this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
|
||||
this.currentAnim = this._anims[name];
|
||||
this.currentFrame = this.currentAnim.currentFrame;
|
||||
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this.sprite.__tilePattern)
|
||||
{
|
||||
this.__tilePattern = false;
|
||||
this.tilingTexture = false;
|
||||
}
|
||||
|
||||
return this._anims[name];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Check whether the frames in the given array are valid and exist.
|
||||
*
|
||||
* @method Phaser.AnimationManager#validateFrames
|
||||
* @param {Array} frames - An array of frames to be validated.
|
||||
* @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
|
||||
* @return {boolean} True if all given Frames are valid, otherwise false.
|
||||
*/
|
||||
validateFrames: function (frames, useNumericIndex) {
|
||||
|
||||
if (typeof useNumericIndex == 'undefined') { useNumericIndex = true; }
|
||||
|
||||
for (var i = 0; i < frames.length; i++)
|
||||
{
|
||||
if (useNumericIndex === true)
|
||||
{
|
||||
if (frames[i] > this._frameData.total)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this._frameData.checkFrameName(frames[i]) === false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
|
||||
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
|
||||
*
|
||||
* @method Phaser.AnimationManager#play
|
||||
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
|
||||
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
|
||||
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
|
||||
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
|
||||
* @return {Phaser.Animation} A reference to playing Animation instance.
|
||||
*/
|
||||
play: function (name, frameRate, loop, killOnComplete) {
|
||||
|
||||
if (this._anims[name])
|
||||
{
|
||||
if (this.currentAnim === this._anims[name])
|
||||
{
|
||||
if (this.currentAnim.isPlaying === false)
|
||||
{
|
||||
this.currentAnim.paused = false;
|
||||
return this.currentAnim.play(frameRate, loop, killOnComplete);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.currentAnim && this.currentAnim.isPlaying)
|
||||
{
|
||||
this.currentAnim.stop();
|
||||
}
|
||||
|
||||
this.currentAnim = this._anims[name];
|
||||
this.currentAnim.paused = false;
|
||||
return this.currentAnim.play(frameRate, loop, killOnComplete);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
|
||||
* The currentAnim property of the AnimationManager is automatically set to the animation given.
|
||||
*
|
||||
* @method Phaser.AnimationManager#stop
|
||||
* @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped.
|
||||
* @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false)
|
||||
*/
|
||||
stop: function (name, resetFrame) {
|
||||
|
||||
if (typeof resetFrame == 'undefined') { resetFrame = false; }
|
||||
|
||||
if (typeof name == 'string')
|
||||
{
|
||||
if (this._anims[name])
|
||||
{
|
||||
this.currentAnim = this._anims[name];
|
||||
this.currentAnim.stop(resetFrame);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.currentAnim)
|
||||
{
|
||||
this.currentAnim.stop(resetFrame);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
|
||||
*
|
||||
* @method Phaser.AnimationManager#update
|
||||
* @protected
|
||||
* @return {boolean} True if a new animation frame has been set, otherwise false.
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
if (this.updateIfVisible && !this.sprite.visible)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.currentAnim && this.currentAnim.update() === true)
|
||||
{
|
||||
this.currentFrame = this.currentAnim.currentFrame;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns an animation that was previously added by name.
|
||||
*
|
||||
* @method Phaser.AnimationManager#getAnimation
|
||||
* @param {string} name - The name of the animation to be returned, e.g. "fire".
|
||||
* @return {Phaser.Animation} The Animation instance, if found, otherwise null.
|
||||
*/
|
||||
getAnimation: function (name) {
|
||||
|
||||
if (typeof name === 'string')
|
||||
{
|
||||
if (this._anims[name])
|
||||
{
|
||||
return this._anims[name];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Refreshes the current frame data back to the parent Sprite and also resets the texture data.
|
||||
*
|
||||
* @method Phaser.AnimationManager#refreshFrame
|
||||
*/
|
||||
refreshFrame: function () {
|
||||
|
||||
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this.sprite.__tilePattern)
|
||||
{
|
||||
this.__tilePattern = false;
|
||||
this.tilingTexture = false;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Destroys all references this AnimationManager contains.
|
||||
* Iterates through the list of animations stored in this manager and calls destroy on each of them.
|
||||
*
|
||||
* @method Phaser.AnimationManager#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
var anim = null;
|
||||
|
||||
for (var anim in this._anims)
|
||||
{
|
||||
if (this._anims.hasOwnProperty(anim))
|
||||
{
|
||||
this._anims[anim].destroy();
|
||||
}
|
||||
}
|
||||
|
||||
this._anims = {};
|
||||
this._frameData = null;
|
||||
this._frameIndex = 0;
|
||||
this.currentAnim = null;
|
||||
this.currentFrame = null;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
|
||||
|
||||
/**
|
||||
* @name Phaser.AnimationManager#frameData
|
||||
* @property {Phaser.FrameData} frameData - The current animations FrameData.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
|
||||
|
||||
get: function () {
|
||||
return this._frameData;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.AnimationManager#frameTotal
|
||||
* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this._frameData)
|
||||
{
|
||||
return this._frameData.total;
|
||||
}
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.AnimationManager#paused
|
||||
* @property {boolean} paused - Gets and sets the paused state of the current animation.
|
||||
*/
|
||||
Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.currentAnim.isPaused;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.currentAnim.paused = value;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.AnimationManager#frame
|
||||
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
return this._frameIndex;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
|
||||
{
|
||||
this.currentFrame = this._frameData.getFrame(value);
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
this._frameIndex = value;
|
||||
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this.sprite.__tilePattern)
|
||||
{
|
||||
this.__tilePattern = false;
|
||||
this.tilingTexture = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.AnimationManager#frameName
|
||||
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
return this.currentFrame.name;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
|
||||
{
|
||||
this.currentFrame = this._frameData.getFrameByName(value);
|
||||
|
||||
if (this.currentFrame)
|
||||
{
|
||||
this._frameIndex = this.currentFrame.index;
|
||||
this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
|
||||
|
||||
if (this.sprite.__tilePattern)
|
||||
{
|
||||
this.__tilePattern = false;
|
||||
this.tilingTexture = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
console.warn('Cannot set frameName: ' + value);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
315
src/animation/AnimationParser.js
Normal file
315
src/animation/AnimationParser.js
Normal file
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
|
||||
*
|
||||
* @class Phaser.AnimationParser
|
||||
*/
|
||||
Phaser.AnimationParser = {
|
||||
|
||||
/**
|
||||
* Parse a Sprite Sheet and extract the animation frame data from it.
|
||||
*
|
||||
* @method Phaser.AnimationParser.spriteSheet
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {string} key - The Game.Cache asset key of the Sprite Sheet image.
|
||||
* @param {number} frameWidth - The fixed width of each frame of the animation.
|
||||
* @param {number} frameHeight - The fixed height of each frame of the animation.
|
||||
* @param {number} [frameMax=-1] - The total number of animation frames to extact from the Sprite Sheet. The default value of -1 means "extract all frames".
|
||||
* @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
|
||||
* @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
|
||||
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
|
||||
*/
|
||||
spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
|
||||
|
||||
// How big is our image?
|
||||
var img = game.cache.getImage(key);
|
||||
|
||||
if (img == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var width = img.width;
|
||||
var height = img.height;
|
||||
|
||||
if (frameWidth <= 0)
|
||||
{
|
||||
frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
|
||||
}
|
||||
|
||||
if (frameHeight <= 0)
|
||||
{
|
||||
frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
|
||||
}
|
||||
|
||||
var row = Math.floor((width - margin) / (frameWidth + spacing));
|
||||
var column = Math.floor((height - margin) / (frameHeight + spacing));
|
||||
var total = row * column;
|
||||
|
||||
if (frameMax !== -1)
|
||||
{
|
||||
total = frameMax;
|
||||
}
|
||||
|
||||
// Zero or smaller than frame sizes?
|
||||
if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
|
||||
{
|
||||
console.warn("Phaser.AnimationParser.spriteSheet: width/height zero or width/height < given frameWidth/frameHeight");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Let's create some frames then
|
||||
var data = new Phaser.FrameData();
|
||||
var x = margin;
|
||||
var y = margin;
|
||||
|
||||
for (var i = 0; i < total; i++)
|
||||
{
|
||||
var uuid = game.rnd.uuid();
|
||||
|
||||
data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '', uuid));
|
||||
|
||||
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
|
||||
x: x,
|
||||
y: y,
|
||||
width: frameWidth,
|
||||
height: frameHeight
|
||||
});
|
||||
|
||||
x += frameWidth + spacing;
|
||||
|
||||
if (x + frameWidth > width)
|
||||
{
|
||||
x = margin;
|
||||
y += frameHeight + spacing;
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Parse the JSON data and extract the animation frame data from it.
|
||||
*
|
||||
* @method Phaser.AnimationParser.JSONData
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Object} json - The JSON data from the Texture Atlas. Must be in Array format.
|
||||
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
|
||||
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
|
||||
*/
|
||||
JSONData: function (game, json, cacheKey) {
|
||||
|
||||
// Malformed?
|
||||
if (!json['frames'])
|
||||
{
|
||||
console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
|
||||
console.log(json);
|
||||
return;
|
||||
}
|
||||
|
||||
// Let's create some frames then
|
||||
var data = new Phaser.FrameData();
|
||||
|
||||
// By this stage frames is a fully parsed array
|
||||
var frames = json['frames'];
|
||||
var newFrame;
|
||||
|
||||
for (var i = 0; i < frames.length; i++)
|
||||
{
|
||||
var uuid = game.rnd.uuid();
|
||||
|
||||
newFrame = data.addFrame(new Phaser.Frame(
|
||||
i,
|
||||
frames[i].frame.x,
|
||||
frames[i].frame.y,
|
||||
frames[i].frame.w,
|
||||
frames[i].frame.h,
|
||||
frames[i].filename,
|
||||
uuid
|
||||
));
|
||||
|
||||
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
|
||||
x: frames[i].frame.x,
|
||||
y: frames[i].frame.y,
|
||||
width: frames[i].frame.w,
|
||||
height: frames[i].frame.h
|
||||
});
|
||||
|
||||
if (frames[i].trimmed)
|
||||
{
|
||||
newFrame.setTrim(
|
||||
frames[i].trimmed,
|
||||
frames[i].sourceSize.w,
|
||||
frames[i].sourceSize.h,
|
||||
frames[i].spriteSourceSize.x,
|
||||
frames[i].spriteSourceSize.y,
|
||||
frames[i].spriteSourceSize.w,
|
||||
frames[i].spriteSourceSize.h
|
||||
);
|
||||
|
||||
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frames[i].spriteSourceSize.x, frames[i].spriteSourceSize.y, frames[i].sourceSize.w, frames[i].sourceSize.h);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Parse the JSON data and extract the animation frame data from it.
|
||||
*
|
||||
* @method Phaser.AnimationParser.JSONDataHash
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
|
||||
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
|
||||
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
|
||||
*/
|
||||
JSONDataHash: function (game, json, cacheKey) {
|
||||
|
||||
// Malformed?
|
||||
if (!json['frames'])
|
||||
{
|
||||
console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
|
||||
console.log(json);
|
||||
return;
|
||||
}
|
||||
|
||||
// Let's create some frames then
|
||||
var data = new Phaser.FrameData();
|
||||
|
||||
// By this stage frames is a fully parsed array
|
||||
var frames = json['frames'];
|
||||
var newFrame;
|
||||
var i = 0;
|
||||
|
||||
for (var key in frames)
|
||||
{
|
||||
var uuid = game.rnd.uuid();
|
||||
|
||||
newFrame = data.addFrame(new Phaser.Frame(
|
||||
i,
|
||||
frames[key].frame.x,
|
||||
frames[key].frame.y,
|
||||
frames[key].frame.w,
|
||||
frames[key].frame.h,
|
||||
key,
|
||||
uuid
|
||||
));
|
||||
|
||||
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
|
||||
x: frames[key].frame.x,
|
||||
y: frames[key].frame.y,
|
||||
width: frames[key].frame.w,
|
||||
height: frames[key].frame.h
|
||||
});
|
||||
|
||||
if (frames[key].trimmed)
|
||||
{
|
||||
newFrame.setTrim(
|
||||
frames[key].trimmed,
|
||||
frames[key].sourceSize.w,
|
||||
frames[key].sourceSize.h,
|
||||
frames[key].spriteSourceSize.x,
|
||||
frames[key].spriteSourceSize.y,
|
||||
frames[key].spriteSourceSize.w,
|
||||
frames[key].spriteSourceSize.h
|
||||
);
|
||||
|
||||
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frames[key].spriteSourceSize.x, frames[key].spriteSourceSize.y, frames[key].sourceSize.w, frames[key].sourceSize.h);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Parse the XML data and extract the animation frame data from it.
|
||||
*
|
||||
* @method Phaser.AnimationParser.XMLData
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
|
||||
* @param {string} cacheKey - The Game.Cache asset key of the texture image.
|
||||
* @return {Phaser.FrameData} A FrameData object containing the parsed frames.
|
||||
*/
|
||||
XMLData: function (game, xml, cacheKey) {
|
||||
|
||||
// Malformed?
|
||||
if (!xml.getElementsByTagName('TextureAtlas'))
|
||||
{
|
||||
console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
|
||||
return;
|
||||
}
|
||||
|
||||
// Let's create some frames then
|
||||
var data = new Phaser.FrameData();
|
||||
var frames = xml.getElementsByTagName('SubTexture');
|
||||
var newFrame;
|
||||
|
||||
var uuid;
|
||||
var name;
|
||||
var frame;
|
||||
var x;
|
||||
var y;
|
||||
var width;
|
||||
var height;
|
||||
var frameX;
|
||||
var frameY;
|
||||
var frameWidth;
|
||||
var frameHeight;
|
||||
|
||||
for (var i = 0; i < frames.length; i++)
|
||||
{
|
||||
uuid = game.rnd.uuid();
|
||||
|
||||
frame = frames[i].attributes;
|
||||
|
||||
name = frame.name.nodeValue;
|
||||
x = parseInt(frame.x.nodeValue, 10);
|
||||
y = parseInt(frame.y.nodeValue, 10);
|
||||
width = parseInt(frame.width.nodeValue, 10);
|
||||
height = parseInt(frame.height.nodeValue, 10);
|
||||
|
||||
frameX = null;
|
||||
frameY = null;
|
||||
|
||||
if (frame.frameX)
|
||||
{
|
||||
frameX = Math.abs(parseInt(frame.frameX.nodeValue, 10));
|
||||
frameY = Math.abs(parseInt(frame.frameY.nodeValue, 10));
|
||||
frameWidth = parseInt(frame.frameWidth.nodeValue, 10);
|
||||
frameHeight = parseInt(frame.frameHeight.nodeValue, 10);
|
||||
}
|
||||
|
||||
newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name, uuid));
|
||||
|
||||
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], {
|
||||
x: x,
|
||||
y: y,
|
||||
width: width,
|
||||
height: height
|
||||
});
|
||||
|
||||
// Trimmed?
|
||||
if (frameX !== null || frameY !== null)
|
||||
{
|
||||
newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
|
||||
|
||||
PIXI.TextureCache[uuid].trim = new Phaser.Rectangle(frameX, frameY, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
184
src/animation/Frame.js
Normal file
184
src/animation/Frame.js
Normal file
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A Frame is a single frame of an animation and is part of a FrameData collection.
|
||||
*
|
||||
* @class Phaser.Frame
|
||||
* @constructor
|
||||
* @param {number} index - The index of this Frame within the FrameData set it is being added to.
|
||||
* @param {number} x - X position of the frame within the texture image.
|
||||
* @param {number} y - Y position of the frame within the texture image.
|
||||
* @param {number} width - Width of the frame within the texture image.
|
||||
* @param {number} height - Height of the frame within the texture image.
|
||||
* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
|
||||
* @param {string} uuid - Internal UUID key.
|
||||
*/
|
||||
Phaser.Frame = function (index, x, y, width, height, name, uuid) {
|
||||
|
||||
/**
|
||||
* @property {number} index - The index of this Frame within the FrameData set it is being added to.
|
||||
*/
|
||||
this.index = index;
|
||||
|
||||
/**
|
||||
* @property {number} x - X position within the image to cut from.
|
||||
*/
|
||||
this.x = x;
|
||||
|
||||
/**
|
||||
* @property {number} y - Y position within the image to cut from.
|
||||
*/
|
||||
this.y = y;
|
||||
|
||||
/**
|
||||
* @property {number} width - Width of the frame.
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - Height of the frame.
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* @property {string} name - Useful for Texture Atlas files (is set to the filename value).
|
||||
*/
|
||||
this.name = name;
|
||||
|
||||
/**
|
||||
* @property {string} uuid - A link to the PIXI.TextureCache entry.
|
||||
*/
|
||||
this.uuid = uuid;
|
||||
|
||||
/**
|
||||
* @property {number} centerX - Center X position within the image to cut from.
|
||||
*/
|
||||
this.centerX = Math.floor(width / 2);
|
||||
|
||||
/**
|
||||
* @property {number} centerY - Center Y position within the image to cut from.
|
||||
*/
|
||||
this.centerY = Math.floor(height / 2);
|
||||
|
||||
/**
|
||||
* @property {number} distance - The distance from the top left to the bottom-right of this Frame.
|
||||
*/
|
||||
this.distance = Phaser.Math.distance(0, 0, width, height);
|
||||
|
||||
/**
|
||||
* @property {boolean} rotated - Rotated? (not yet implemented)
|
||||
* @default
|
||||
*/
|
||||
this.rotated = false;
|
||||
|
||||
/**
|
||||
* @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
|
||||
* @default 'cw'
|
||||
*/
|
||||
this.rotationDirection = 'cw';
|
||||
|
||||
/**
|
||||
* @property {boolean} trimmed - Was it trimmed when packed?
|
||||
* @default
|
||||
*/
|
||||
this.trimmed = false;
|
||||
|
||||
/**
|
||||
* @property {number} sourceSizeW - Width of the original sprite.
|
||||
*/
|
||||
this.sourceSizeW = width;
|
||||
|
||||
/**
|
||||
* @property {number} sourceSizeH - Height of the original sprite.
|
||||
*/
|
||||
this.sourceSizeH = height;
|
||||
|
||||
/**
|
||||
* @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
|
||||
* @default
|
||||
*/
|
||||
this.spriteSourceSizeX = 0;
|
||||
|
||||
/**
|
||||
* @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
|
||||
* @default
|
||||
*/
|
||||
this.spriteSourceSizeY = 0;
|
||||
|
||||
/**
|
||||
* @property {number} spriteSourceSizeW - Width of the trimmed sprite.
|
||||
* @default
|
||||
*/
|
||||
this.spriteSourceSizeW = 0;
|
||||
|
||||
/**
|
||||
* @property {number} spriteSourceSizeH - Height of the trimmed sprite.
|
||||
* @default
|
||||
*/
|
||||
this.spriteSourceSizeH = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Frame.prototype = {
|
||||
|
||||
/**
|
||||
* If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
|
||||
*
|
||||
* @method Phaser.Frame#setTrim
|
||||
* @param {boolean} trimmed - If this frame was trimmed or not.
|
||||
* @param {number} actualWidth - The width of the frame before being trimmed.
|
||||
* @param {number} actualHeight - The height of the frame before being trimmed.
|
||||
* @param {number} destX - The destination X position of the trimmed frame for display.
|
||||
* @param {number} destY - The destination Y position of the trimmed frame for display.
|
||||
* @param {number} destWidth - The destination width of the trimmed frame for display.
|
||||
* @param {number} destHeight - The destination height of the trimmed frame for display.
|
||||
*/
|
||||
setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
|
||||
|
||||
this.trimmed = trimmed;
|
||||
|
||||
if (trimmed)
|
||||
{
|
||||
this.width = actualWidth;
|
||||
this.height = actualHeight;
|
||||
this.sourceSizeW = actualWidth;
|
||||
this.sourceSizeH = actualHeight;
|
||||
this.centerX = Math.floor(actualWidth / 2);
|
||||
this.centerY = Math.floor(actualHeight / 2);
|
||||
this.spriteSourceSizeX = destX;
|
||||
this.spriteSourceSizeY = destY;
|
||||
this.spriteSourceSizeW = destWidth;
|
||||
this.spriteSourceSizeH = destHeight;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a Rectangle set to the dimensions of this Frame.
|
||||
*
|
||||
* @method Phaser.Frame#getRect
|
||||
* @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
|
||||
* @return {Phaser.Rectangle} A rectangle.
|
||||
*/
|
||||
getRect: function (out) {
|
||||
|
||||
if (typeof out === 'undefined')
|
||||
{
|
||||
out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.setTo(this.x, this.y, this.width, this.height);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Frame.prototype.constructor = Phaser.Frame;
|
||||
239
src/animation/FrameData.js
Normal file
239
src/animation/FrameData.js
Normal file
@@ -0,0 +1,239 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
|
||||
*
|
||||
* @class Phaser.FrameData
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.FrameData = function () {
|
||||
|
||||
/**
|
||||
* @property {Array} _frames - Local array of frames.
|
||||
* @private
|
||||
*/
|
||||
this._frames = [];
|
||||
|
||||
|
||||
/**
|
||||
* @property {Array} _frameNames - Local array of frame names for name to index conversions.
|
||||
* @private
|
||||
*/
|
||||
this._frameNames = [];
|
||||
|
||||
};
|
||||
|
||||
Phaser.FrameData.prototype = {
|
||||
|
||||
/**
|
||||
* Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
|
||||
*
|
||||
* @method Phaser.FrameData#addFrame
|
||||
* @param {Phaser.Frame} frame - The frame to add to this FrameData set.
|
||||
* @return {Phaser.Frame} The frame that was just added.
|
||||
*/
|
||||
addFrame: function (frame) {
|
||||
|
||||
frame.index = this._frames.length;
|
||||
|
||||
this._frames.push(frame);
|
||||
|
||||
if (frame.name !== '')
|
||||
{
|
||||
this._frameNames[frame.name] = frame.index;
|
||||
}
|
||||
|
||||
return frame;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a Frame by its numerical index.
|
||||
*
|
||||
* @method Phaser.FrameData#getFrame
|
||||
* @param {number} index - The index of the frame you want to get.
|
||||
* @return {Phaser.Frame} The frame, if found.
|
||||
*/
|
||||
getFrame: function (index) {
|
||||
|
||||
if (index > this._frames.length)
|
||||
{
|
||||
index = 0;
|
||||
}
|
||||
|
||||
return this._frames[index];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a Frame by its frame name.
|
||||
*
|
||||
* @method Phaser.FrameData#getFrameByName
|
||||
* @param {string} name - The name of the frame you want to get.
|
||||
* @return {Phaser.Frame} The frame, if found.
|
||||
*/
|
||||
getFrameByName: function (name) {
|
||||
|
||||
if (typeof this._frameNames[name] === 'number')
|
||||
{
|
||||
return this._frames[this._frameNames[name]];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if there is a Frame with the given name.
|
||||
*
|
||||
* @method Phaser.FrameData#checkFrameName
|
||||
* @param {string} name - The name of the frame you want to check.
|
||||
* @return {boolean} True if the frame is found, otherwise false.
|
||||
*/
|
||||
checkFrameName: function (name) {
|
||||
|
||||
if (this._frameNames[name] == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
|
||||
*
|
||||
* @method Phaser.FrameData#getFrameRange
|
||||
* @param {number} start - The starting frame index.
|
||||
* @param {number} end - The ending frame index.
|
||||
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
|
||||
* @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
|
||||
*/
|
||||
getFrameRange: function (start, end, output) {
|
||||
|
||||
if (typeof output === "undefined") { output = []; }
|
||||
|
||||
for (var i = start; i <= end; i++)
|
||||
{
|
||||
output.push(this._frames[i]);
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns all of the Frames in this FrameData set where the frame index is found in the input array.
|
||||
* The frames are returned in the output array, or if none is provided in a new Array object.
|
||||
*
|
||||
* @method Phaser.FrameData#getFrames
|
||||
* @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
|
||||
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
|
||||
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
|
||||
* @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
|
||||
*/
|
||||
getFrames: function (frames, useNumericIndex, output) {
|
||||
|
||||
if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
|
||||
if (typeof output === "undefined") { output = []; }
|
||||
|
||||
if (typeof frames === "undefined" || frames.length === 0)
|
||||
{
|
||||
// No input array, so we loop through all frames
|
||||
for (var i = 0; i < this._frames.length; i++)
|
||||
{
|
||||
// We only need the indexes
|
||||
output.push(this._frames[i]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Input array given, loop through that instead
|
||||
for (var i = 0, len = frames.length; i < len; i++)
|
||||
{
|
||||
// Does the input array contain names or indexes?
|
||||
if (useNumericIndex)
|
||||
{
|
||||
// The actual frame
|
||||
output.push(this.getFrame(frames[i]));
|
||||
}
|
||||
else
|
||||
{
|
||||
// The actual frame
|
||||
output.push(this.getFrameByName(frames[i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns all of the Frame indexes in this FrameData set.
|
||||
* The frames indexes are returned in the output array, or if none is provided in a new Array object.
|
||||
*
|
||||
* @method Phaser.FrameData#getFrameIndexes
|
||||
* @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned.
|
||||
* @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
|
||||
* @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
|
||||
* @return {Array} An array of all Frame indexes matching the given names or IDs.
|
||||
*/
|
||||
getFrameIndexes: function (frames, useNumericIndex, output) {
|
||||
|
||||
if (typeof useNumericIndex === "undefined") { useNumericIndex = true; }
|
||||
if (typeof output === "undefined") { output = []; }
|
||||
|
||||
if (typeof frames === "undefined" || frames.length === 0)
|
||||
{
|
||||
// No frames array, so we loop through all frames
|
||||
for (var i = 0, len = this._frames.length; i < len; i++)
|
||||
{
|
||||
output.push(this._frames[i].index);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Input array given, loop through that instead
|
||||
for (var i = 0, len = frames.length; i < len; i++)
|
||||
{
|
||||
// Does the frames array contain names or indexes?
|
||||
if (useNumericIndex)
|
||||
{
|
||||
output.push(frames[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.getFrameByName(frames[i]))
|
||||
{
|
||||
output.push(this.getFrameByName(frames[i]).index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.FrameData.prototype.constructor = Phaser.FrameData;
|
||||
|
||||
/**
|
||||
* @name Phaser.FrameData#total
|
||||
* @property {number} total - The total number of frames in this FrameData set.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.FrameData.prototype, "total", {
|
||||
|
||||
get: function () {
|
||||
return this._frames.length;
|
||||
}
|
||||
|
||||
});
|
||||
189
src/core/ArrayList.js
Normal file
189
src/core/ArrayList.js
Normal file
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A set data structure. Allows items to add themselves to and remove themselves from the set. Items can only exist once in the set.
|
||||
*
|
||||
* @class Phaser.ArrayList
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.ArrayList = function () {
|
||||
|
||||
/**
|
||||
* @property {number} total - Number of objects in the list.
|
||||
* @default
|
||||
*/
|
||||
this.total = 0;
|
||||
|
||||
/**
|
||||
* @property {number} position - Current cursor position.
|
||||
* @default
|
||||
*/
|
||||
this.position = 0;
|
||||
|
||||
/**
|
||||
* @property {array} list - The list.
|
||||
*/
|
||||
this.list = [];
|
||||
|
||||
};
|
||||
|
||||
Phaser.ArrayList.prototype = {
|
||||
|
||||
/**
|
||||
* Adds a new element to this list. The item can only exist in the list once.
|
||||
*
|
||||
* @method Phaser.ArrayList#add
|
||||
* @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
|
||||
* @return {object} The child that was added.
|
||||
*/
|
||||
add: function (child) {
|
||||
|
||||
if (!this.exists(child))
|
||||
{
|
||||
this.list.push(child);
|
||||
this.total++;
|
||||
}
|
||||
|
||||
return child;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets the index of the child in the list, or -1 if it isn't in the list.
|
||||
*
|
||||
* @method Phaser.ArrayList#getIndex
|
||||
* @param {object} child - The element to get the list index for.
|
||||
* @return {number} The index of the child or -1 if not found.
|
||||
*/
|
||||
getIndex: function (child) {
|
||||
|
||||
return this.list.indexOf(child);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks for the child within this list.
|
||||
*
|
||||
* @method Phaser.ArrayList#exists
|
||||
* @param {object} child - The element to get the list index for.
|
||||
* @return {boolean} True if the child is found in the list, otherwise false.
|
||||
*/
|
||||
exists: function (child) {
|
||||
|
||||
return (this.list.indexOf(child) > -1);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the list length and drops all items in the list.
|
||||
*
|
||||
* @method Phaser.ArrayList#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
this.list.length = 0;
|
||||
this.total = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes the given element from this list if it exists.
|
||||
*
|
||||
* @method Phaser.ArrayList#remove
|
||||
* @param {object} child - The child to be removed from the list.
|
||||
* @return {object} child - The child that was removed.
|
||||
*/
|
||||
remove: function (child) {
|
||||
|
||||
var idx = this.list.indexOf(child);
|
||||
|
||||
if (idx > -1)
|
||||
{
|
||||
this.list.splice(idx, 1);
|
||||
this.total--;
|
||||
return child;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Calls a function on all members of this list, using the member as the context for the callback.
|
||||
* The function must exist on the member.
|
||||
*
|
||||
* @method Phaser.ArrayList#callAll
|
||||
* @param {function} callback - The function to call.
|
||||
* @param {...*} parameter - Additional parameters that will be passed to the callback.
|
||||
*/
|
||||
callAll: function (callback) {
|
||||
|
||||
var args = Array.prototype.splice.call(arguments, 1);
|
||||
|
||||
var i = this.list.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
if (this.list[i] && this.list[i][callback])
|
||||
{
|
||||
this.list[i][callback].apply(this.list[i], args);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets the cursor to the first item in the list and returns it.
|
||||
*
|
||||
* @name Phaser.ArrayList#first
|
||||
* @property {object} first - The first item in the list.
|
||||
*/
|
||||
Object.defineProperty(Phaser.ArrayList.prototype, "first", {
|
||||
|
||||
get: function () {
|
||||
|
||||
this.position = 0;
|
||||
|
||||
if (this.total > 0)
|
||||
{
|
||||
return this.list[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gets the next item in the list and returns it, advancing the cursor.
|
||||
*
|
||||
* @name Phaser.ArrayList#next
|
||||
* @property {object} next - Advanced the cursor and return.
|
||||
*/
|
||||
Object.defineProperty(Phaser.ArrayList.prototype, "next", {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.position < this.total)
|
||||
{
|
||||
this.position++;
|
||||
|
||||
return this.list[this.position];
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Phaser.ArrayList.prototype.constructor = Phaser.ArrayList;
|
||||
446
src/core/Camera.js
Normal file
446
src/core/Camera.js
Normal file
@@ -0,0 +1,446 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view.
|
||||
* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
|
||||
*
|
||||
* @class Phaser.Camera
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Game reference to the currently running game.
|
||||
* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
|
||||
* @param {number} x - Position of the camera on the X axis
|
||||
* @param {number} y - Position of the camera on the Y axis
|
||||
* @param {number} width - The width of the view rectangle
|
||||
* @param {number} height - The height of the view rectangle
|
||||
*/
|
||||
Phaser.Camera = function (game, id, x, y, width, height) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.World} world - A reference to the game world.
|
||||
*/
|
||||
this.world = game.world;
|
||||
|
||||
/**
|
||||
* @property {number} id - Reserved for future multiple camera set-ups.
|
||||
* @default
|
||||
*/
|
||||
this.id = 0;
|
||||
|
||||
/**
|
||||
* Camera view.
|
||||
* The view into the world we wish to render (by default the game dimensions).
|
||||
* The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
|
||||
* Objects outside of this view are not rendered if set to camera cull.
|
||||
* @property {Phaser.Rectangle} view
|
||||
*/
|
||||
this.view = new Phaser.Rectangle(x, y, width, height);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling.
|
||||
*/
|
||||
this.screenView = new Phaser.Rectangle(x, y, width, height);
|
||||
|
||||
/**
|
||||
* The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World.
|
||||
* The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound
|
||||
* at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the center of the world.
|
||||
* @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
|
||||
*/
|
||||
this.bounds = new Phaser.Rectangle(x, y, width, height);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause camera moving.
|
||||
*/
|
||||
this.deadzone = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} visible - Whether this camera is visible or not.
|
||||
* @default
|
||||
*/
|
||||
this.visible = true;
|
||||
|
||||
/**
|
||||
* @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
|
||||
*/
|
||||
this.atLimit = { x: false, y: false };
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
|
||||
* @default
|
||||
*/
|
||||
this.target = null;
|
||||
|
||||
/**
|
||||
* @property {number} edge - Edge property.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._edge = 0;
|
||||
|
||||
/**
|
||||
* @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot
|
||||
*/
|
||||
this.displayObject = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot
|
||||
*/
|
||||
this.scale = null;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Camera.FOLLOW_LOCKON = 0;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Camera.FOLLOW_PLATFORMER = 1;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Camera.FOLLOW_TOPDOWN = 2;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
|
||||
|
||||
Phaser.Camera.prototype = {
|
||||
|
||||
/**
|
||||
* Tells this camera which sprite to follow.
|
||||
* @method Phaser.Camera#follow
|
||||
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
|
||||
* @param {number} [style] - Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow().
|
||||
*/
|
||||
follow: function (target, style) {
|
||||
|
||||
if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; }
|
||||
|
||||
this.target = target;
|
||||
|
||||
var helper;
|
||||
|
||||
switch (style) {
|
||||
|
||||
case Phaser.Camera.FOLLOW_PLATFORMER:
|
||||
var w = this.width / 8;
|
||||
var h = this.height / 3;
|
||||
this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
|
||||
break;
|
||||
|
||||
case Phaser.Camera.FOLLOW_TOPDOWN:
|
||||
helper = Math.max(this.width, this.height) / 4;
|
||||
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
|
||||
break;
|
||||
|
||||
case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
|
||||
helper = Math.max(this.width, this.height) / 8;
|
||||
this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
|
||||
break;
|
||||
|
||||
case Phaser.Camera.FOLLOW_LOCKON:
|
||||
this.deadzone = null;
|
||||
break;
|
||||
|
||||
default:
|
||||
this.deadzone = null;
|
||||
break;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the Camera follow target to null, stopping it from following an object if it's doing so.
|
||||
*
|
||||
* @method Phaser.Camera#unfollow
|
||||
*/
|
||||
unfollow: function () {
|
||||
|
||||
this.target = null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Move the camera focus on a display object instantly.
|
||||
* @method Phaser.Camera#focusOn
|
||||
* @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
|
||||
*/
|
||||
focusOn: function (displayObject) {
|
||||
|
||||
this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Move the camera focus on a location instantly.
|
||||
* @method Phaser.Camera#focusOnXY
|
||||
* @param {number} x - X position.
|
||||
* @param {number} y - Y position.
|
||||
*/
|
||||
focusOnXY: function (x, y) {
|
||||
|
||||
this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Update focusing and scrolling.
|
||||
* @method Phaser.Camera#update
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
if (this.target)
|
||||
{
|
||||
this.updateTarget();
|
||||
}
|
||||
|
||||
if (this.bounds)
|
||||
{
|
||||
this.checkBounds();
|
||||
}
|
||||
|
||||
this.displayObject.position.x = -this.view.x;
|
||||
this.displayObject.position.y = -this.view.y;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method
|
||||
* @method Phaser.Camera#updateTarget
|
||||
* @private
|
||||
*/
|
||||
updateTarget: function () {
|
||||
|
||||
if (this.deadzone)
|
||||
{
|
||||
this._edge = this.target.x - this.deadzone.x;
|
||||
|
||||
if (this.view.x > this._edge)
|
||||
{
|
||||
this.view.x = this._edge;
|
||||
}
|
||||
|
||||
this._edge = this.target.x + this.target.width - this.deadzone.x - this.deadzone.width;
|
||||
|
||||
if (this.view.x < this._edge)
|
||||
{
|
||||
this.view.x = this._edge;
|
||||
}
|
||||
|
||||
this._edge = this.target.y - this.deadzone.y;
|
||||
|
||||
if (this.view.y > this._edge)
|
||||
{
|
||||
this.view.y = this._edge;
|
||||
}
|
||||
|
||||
this._edge = this.target.y + this.target.height - this.deadzone.y - this.deadzone.height;
|
||||
|
||||
if (this.view.y < this._edge)
|
||||
{
|
||||
this.view.y = this._edge;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.focusOnXY(this.target.x, this.target.y);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Update the Camera bounds to match the game world.
|
||||
* @method Phaser.Camera#setBoundsToWorld
|
||||
*/
|
||||
setBoundsToWorld: function () {
|
||||
|
||||
this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Method called to ensure the camera doesn't venture outside of the game world.
|
||||
* @method Phaser.Camera#checkWorldBounds
|
||||
*/
|
||||
checkBounds: function () {
|
||||
|
||||
this.atLimit.x = false;
|
||||
this.atLimit.y = false;
|
||||
|
||||
// Make sure we didn't go outside the cameras bounds
|
||||
if (this.view.x <= this.bounds.x)
|
||||
{
|
||||
this.atLimit.x = true;
|
||||
this.view.x = this.bounds.x;
|
||||
}
|
||||
|
||||
if (this.view.right >= this.bounds.right)
|
||||
{
|
||||
this.atLimit.x = true;
|
||||
this.view.x = this.bounds.right - this.width;
|
||||
}
|
||||
|
||||
if (this.view.y <= this.bounds.top)
|
||||
{
|
||||
this.atLimit.y = true;
|
||||
this.view.y = this.bounds.top;
|
||||
}
|
||||
|
||||
if (this.view.bottom >= this.bounds.bottom)
|
||||
{
|
||||
this.atLimit.y = true;
|
||||
this.view.y = this.bounds.bottom - this.height;
|
||||
}
|
||||
|
||||
this.view.floor();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A helper function to set both the X and Y properties of the camera at once
|
||||
* without having to use game.camera.x and game.camera.y.
|
||||
*
|
||||
* @method Phaser.Camera#setPosition
|
||||
* @param {number} x - X position.
|
||||
* @param {number} y - Y position.
|
||||
*/
|
||||
setPosition: function (x, y) {
|
||||
|
||||
this.view.x = x;
|
||||
this.view.y = y;
|
||||
|
||||
if (this.bounds)
|
||||
{
|
||||
this.checkBounds();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the size of the view rectangle given the width and height in parameters.
|
||||
*
|
||||
* @method Phaser.Camera#setSize
|
||||
* @param {number} width - The desired width.
|
||||
* @param {number} height - The desired height.
|
||||
*/
|
||||
setSize: function (width, height) {
|
||||
|
||||
this.view.width = width;
|
||||
this.view.height = height;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the camera back to 0,0 and un-follows any object it may have been tracking.
|
||||
*
|
||||
* @method Phaser.Camera#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
this.target = null;
|
||||
this.view.x = 0;
|
||||
this.view.y = 0;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Camera.prototype.constructor = Phaser.Camera;
|
||||
|
||||
/**
|
||||
* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
|
||||
* @name Phaser.Camera#x
|
||||
* @property {number} x - Gets or sets the cameras x position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Camera.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return this.view.x;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.view.x = value;
|
||||
|
||||
if (this.bounds)
|
||||
{
|
||||
this.checkBounds();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
|
||||
* @name Phaser.Camera#y
|
||||
* @property {number} y - Gets or sets the cameras y position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Camera.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return this.view.y;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.view.y = value;
|
||||
|
||||
if (this.bounds)
|
||||
{
|
||||
this.checkBounds();
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
|
||||
* @name Phaser.Camera#width
|
||||
* @property {number} width - Gets or sets the cameras width.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Camera.prototype, "width", {
|
||||
|
||||
get: function () {
|
||||
return this.view.width;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.view.width = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
|
||||
* @name Phaser.Camera#height
|
||||
* @property {number} height - Gets or sets the cameras height.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Camera.prototype, "height", {
|
||||
|
||||
get: function () {
|
||||
return this.view.height;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.view.height = value;
|
||||
}
|
||||
|
||||
});
|
||||
165
src/core/Filter.js
Normal file
165
src/core/Filter.js
Normal file
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a base Filter template to use for any Phaser filter development.
|
||||
*
|
||||
* @class Phaser.Filter
|
||||
* @classdesc Phaser - Filter
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Object} uniforms - Uniform mappings object
|
||||
* @param {Array} fragmentSrc - The fragment shader code.
|
||||
*/
|
||||
Phaser.Filter = function (game, uniforms, fragmentSrc) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
|
||||
* @default
|
||||
*/
|
||||
this.type = Phaser.WEBGL_FILTER;
|
||||
|
||||
/**
|
||||
* An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
|
||||
* For example the blur filter has two passes blurX and blurY.
|
||||
* @property {array} passes - An array of filter objects.
|
||||
* @private
|
||||
*/
|
||||
this.passes = [this];
|
||||
|
||||
/**
|
||||
* @property {array} shaders - Array an array of shaders.
|
||||
* @private
|
||||
*/
|
||||
this.shaders = [];
|
||||
|
||||
/**
|
||||
* @property {boolean} dirty - Internal PIXI var.
|
||||
* @default
|
||||
*/
|
||||
this.dirty = true;
|
||||
|
||||
/**
|
||||
* @property {number} padding - Internal PIXI var.
|
||||
* @default
|
||||
*/
|
||||
this.padding = 0;
|
||||
|
||||
/**
|
||||
* @property {object} uniforms - Default uniform mappings.
|
||||
*/
|
||||
this.uniforms = {
|
||||
|
||||
time: { type: '1f', value: 0 },
|
||||
resolution: { type: '2f', value: { x: 256, y: 256 }},
|
||||
mouse: { type: '2f', value: { x: 0.0, y: 0.0 }}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @property {array} fragmentSrc - The fragment shader code.
|
||||
*/
|
||||
this.fragmentSrc = fragmentSrc || [];
|
||||
|
||||
};
|
||||
|
||||
Phaser.Filter.prototype = {
|
||||
|
||||
/**
|
||||
* Should be over-ridden.
|
||||
* @method Phaser.Filter#init
|
||||
*/
|
||||
init: function () {
|
||||
// This should be over-ridden. Will receive a variable number of arguments.
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the resolution uniforms on the filter.
|
||||
* @method Phaser.Filter#setResolution
|
||||
* @param {number} width - The width of the display.
|
||||
* @param {number} height - The height of the display.
|
||||
*/
|
||||
setResolution: function (width, height) {
|
||||
|
||||
this.uniforms.resolution.value.x = width;
|
||||
this.uniforms.resolution.value.y = height;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the filter.
|
||||
* @method Phaser.Filter#update
|
||||
* @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
|
||||
*/
|
||||
update: function (pointer) {
|
||||
|
||||
if (typeof pointer !== 'undefined')
|
||||
{
|
||||
if (pointer.x > 0)
|
||||
{
|
||||
this.uniforms.mouse.x = pointer.x.toFixed(2);
|
||||
}
|
||||
|
||||
if (pointer.y > 0)
|
||||
{
|
||||
this.uniforms.mouse.y = pointer.y.toFixed(2);
|
||||
}
|
||||
}
|
||||
|
||||
this.uniforms.time.value = this.game.time.totalElapsedSeconds();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear down this Filter and null out references
|
||||
* @method Phaser.Filter#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.game = null;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Filter.prototype.constructor = Phaser.Filter;
|
||||
|
||||
/**
|
||||
* @name Phaser.Filter#width
|
||||
* @property {number} width - The width (resolution uniform)
|
||||
*/
|
||||
Object.defineProperty(Phaser.Filter.prototype, 'width', {
|
||||
|
||||
get: function() {
|
||||
return this.uniforms.resolution.value.x;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
this.uniforms.resolution.value.x = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Filter#height
|
||||
* @property {number} height - The height (resolution uniform)
|
||||
*/
|
||||
Object.defineProperty(Phaser.Filter.prototype, 'height', {
|
||||
|
||||
get: function() {
|
||||
return this.uniforms.resolution.value.y;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
this.uniforms.resolution.value.y = value;
|
||||
}
|
||||
|
||||
});
|
||||
824
src/core/Game.js
Normal file
824
src/core/Game.js
Normal file
@@ -0,0 +1,824 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Game constructor
|
||||
*
|
||||
* Instantiate a new <code>Phaser.Game</code> object.
|
||||
* @class Phaser.Game
|
||||
* @classdesc This is where the magic happens. The Game object is the heart of your game,
|
||||
* providing quick access to common functions and handling the boot process.
|
||||
* "Hell, there are no rules here - we're trying to accomplish something."
|
||||
* Thomas A. Edison
|
||||
* @constructor
|
||||
* @param {number} [width=800] - The width of your game in game pixels.
|
||||
* @param {number} [height=600] - The height of your game in game pixels.
|
||||
* @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
|
||||
* @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
|
||||
* @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
|
||||
* @param {boolean} [transparent=false] - Use a transparent canvas background or not.
|
||||
* @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
|
||||
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
|
||||
*/
|
||||
Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
|
||||
|
||||
/**
|
||||
* @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
|
||||
*/
|
||||
this.id = Phaser.GAMES.push(this) - 1;
|
||||
|
||||
/**
|
||||
* @property {object} config - The Phaser.Game configuration object.
|
||||
*/
|
||||
this.config = null;
|
||||
|
||||
/**
|
||||
* @property {object} physicsConfig - The Phaser.Physics.World configuration object.
|
||||
*/
|
||||
this.physicsConfig = physicsConfig;
|
||||
|
||||
/**
|
||||
* @property {string|HTMLElement} parent - The Games DOM parent.
|
||||
* @default
|
||||
*/
|
||||
this.parent = '';
|
||||
|
||||
/**
|
||||
* @property {number} width - The Game width (in pixels).
|
||||
* @default
|
||||
*/
|
||||
this.width = 800;
|
||||
|
||||
/**
|
||||
* @property {number} height - The Game height (in pixels).
|
||||
* @default
|
||||
*/
|
||||
this.height = 600;
|
||||
|
||||
/**
|
||||
* @property {boolean} transparent - Use a transparent canvas background or not.
|
||||
* @default
|
||||
*/
|
||||
this.transparent = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
|
||||
* @default
|
||||
*/
|
||||
this.antialias = true;
|
||||
|
||||
/**
|
||||
* @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
|
||||
*/
|
||||
this.renderer = null;
|
||||
|
||||
/**
|
||||
* @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS or Phaser.WEBGL.
|
||||
*/
|
||||
this.renderType = Phaser.AUTO;
|
||||
|
||||
/**
|
||||
* @property {Phaser.StateManager} state - The StateManager.
|
||||
*/
|
||||
this.state = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} isBooted - Whether the game engine is booted, aka available.
|
||||
* @default
|
||||
*/
|
||||
this.isBooted = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} id -Is game running or paused?
|
||||
* @default
|
||||
*/
|
||||
this.isRunning = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
|
||||
*/
|
||||
this.raf = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
|
||||
*/
|
||||
this.add = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
|
||||
*/
|
||||
this.make = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Cache} cache - Reference to the assets cache.
|
||||
*/
|
||||
this.cache = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Input} input - Reference to the input manager
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Loader} load - Reference to the assets loader.
|
||||
*/
|
||||
this.load = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Math} math - Reference to the math helper.
|
||||
*/
|
||||
this.math = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Net} net - Reference to the network class.
|
||||
*/
|
||||
this.net = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.ScaleManager} scale - The game scale manager.
|
||||
*/
|
||||
this.scale = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.SoundManager} sound - Reference to the sound manager.
|
||||
*/
|
||||
this.sound = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Stage} stage - Reference to the stage.
|
||||
*/
|
||||
this.stage = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Time} time - Reference to the core game clock.
|
||||
*/
|
||||
this.time = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.TweenManager} tweens - Reference to the tween manager.
|
||||
*/
|
||||
this.tweens = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.World} world - Reference to the world.
|
||||
*/
|
||||
this.world = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics} physics - Reference to the physics manager.
|
||||
*/
|
||||
this.physics = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
|
||||
*/
|
||||
this.rnd = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Device} device - Contains device information and capabilities.
|
||||
*/
|
||||
this.device = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Camera} camera - A handy reference to world.camera.
|
||||
*/
|
||||
this.camera = null;
|
||||
|
||||
/**
|
||||
* @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
|
||||
*/
|
||||
this.canvas = null;
|
||||
|
||||
/**
|
||||
* @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
|
||||
*/
|
||||
this.context = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie.
|
||||
*/
|
||||
this.debug = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Particles} particles - The Particle Manager.
|
||||
*/
|
||||
this.particles = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
|
||||
* @default
|
||||
* @readonly
|
||||
*/
|
||||
this.stepping = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
|
||||
* @default
|
||||
* @readonly
|
||||
*/
|
||||
this.pendingStep = false;
|
||||
|
||||
/**
|
||||
* @property {number} stepCount - When stepping is enabled this contains the current step cycle.
|
||||
* @default
|
||||
* @readonly
|
||||
*/
|
||||
this.stepCount = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onPause - This event is fired when the game pauses.
|
||||
*/
|
||||
this.onPause = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
|
||||
*/
|
||||
this.onResume = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
|
||||
*/
|
||||
this.onBlur = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
|
||||
*/
|
||||
this.onFocus = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} _paused - Is game paused?
|
||||
* @private
|
||||
*/
|
||||
this._paused = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} _codePaused - Was the game paused via code or a visibility change?
|
||||
* @private
|
||||
*/
|
||||
this._codePaused = false;
|
||||
|
||||
// Parse the configuration object (if any)
|
||||
if (arguments.length === 1 && typeof arguments[0] === 'object')
|
||||
{
|
||||
this.parseConfig(arguments[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (typeof width !== 'undefined')
|
||||
{
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
if (typeof height !== 'undefined')
|
||||
{
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
if (typeof renderer !== 'undefined')
|
||||
{
|
||||
this.renderer = renderer;
|
||||
this.renderType = renderer;
|
||||
}
|
||||
|
||||
if (typeof parent !== 'undefined')
|
||||
{
|
||||
this.parent = parent;
|
||||
}
|
||||
|
||||
if (typeof transparent !== 'undefined')
|
||||
{
|
||||
this.transparent = transparent;
|
||||
}
|
||||
|
||||
if (typeof antialias !== 'undefined')
|
||||
{
|
||||
this.antialias = antialias;
|
||||
}
|
||||
|
||||
this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
|
||||
|
||||
this.state = new Phaser.StateManager(this, state);
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._onBoot = function () {
|
||||
return _this.boot();
|
||||
};
|
||||
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive')
|
||||
{
|
||||
window.setTimeout(this._onBoot, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
document.addEventListener('DOMContentLoaded', this._onBoot, false);
|
||||
window.addEventListener('load', this._onBoot, false);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Game.prototype = {
|
||||
|
||||
/**
|
||||
* Parses a Game configuration object.
|
||||
*
|
||||
* @method Phaser.Game#parseConfig
|
||||
* @protected
|
||||
*/
|
||||
parseConfig: function (config) {
|
||||
|
||||
this.config = config;
|
||||
|
||||
if (config['width'])
|
||||
{
|
||||
this.width = Phaser.Utils.parseDimension(config['width'], 0);
|
||||
}
|
||||
|
||||
if (config['height'])
|
||||
{
|
||||
this.height = Phaser.Utils.parseDimension(config['height'], 1);
|
||||
}
|
||||
|
||||
if (config['renderer'])
|
||||
{
|
||||
this.renderer = config['renderer'];
|
||||
this.renderType = config['renderer'];
|
||||
}
|
||||
|
||||
if (config['parent'])
|
||||
{
|
||||
this.parent = config['parent'];
|
||||
}
|
||||
|
||||
if (config['transparent'])
|
||||
{
|
||||
this.transparent = config['transparent'];
|
||||
}
|
||||
|
||||
if (config['antialias'])
|
||||
{
|
||||
this.antialias = config['antialias'];
|
||||
}
|
||||
|
||||
if (config['physicsConfig'])
|
||||
{
|
||||
this.physicsConfig = config['physicsConfig'];
|
||||
}
|
||||
|
||||
var seed = [(Date.now() * Math.random()).toString()];
|
||||
|
||||
if (config['seed'])
|
||||
{
|
||||
seed = config['seed'];
|
||||
}
|
||||
|
||||
this.rnd = new Phaser.RandomDataGenerator(seed);
|
||||
|
||||
var state = null;
|
||||
|
||||
if (config['state'])
|
||||
{
|
||||
state = config['state'];
|
||||
}
|
||||
|
||||
this.state = new Phaser.StateManager(this, state);
|
||||
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Initialize engine sub modules and start the game.
|
||||
*
|
||||
* @method Phaser.Game#boot
|
||||
* @protected
|
||||
*/
|
||||
boot: function () {
|
||||
|
||||
if (this.isBooted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!document.body)
|
||||
{
|
||||
window.setTimeout(this._onBoot, 20);
|
||||
}
|
||||
else
|
||||
{
|
||||
document.removeEventListener('DOMContentLoaded', this._onBoot);
|
||||
window.removeEventListener('load', this._onBoot);
|
||||
|
||||
this.onPause = new Phaser.Signal();
|
||||
this.onResume = new Phaser.Signal();
|
||||
this.onBlur = new Phaser.Signal();
|
||||
this.onFocus = new Phaser.Signal();
|
||||
|
||||
this.isBooted = true;
|
||||
|
||||
this.device = new Phaser.Device(this);
|
||||
this.math = Phaser.Math;
|
||||
|
||||
this.stage = new Phaser.Stage(this, this.width, this.height);
|
||||
this.scale = new Phaser.ScaleManager(this, this.width, this.height);
|
||||
|
||||
this.setUpRenderer();
|
||||
|
||||
this.device.checkFullScreenSupport();
|
||||
|
||||
this.world = new Phaser.World(this);
|
||||
this.add = new Phaser.GameObjectFactory(this);
|
||||
this.make = new Phaser.GameObjectCreator(this);
|
||||
this.cache = new Phaser.Cache(this);
|
||||
this.load = new Phaser.Loader(this);
|
||||
this.time = new Phaser.Time(this);
|
||||
this.tweens = new Phaser.TweenManager(this);
|
||||
this.input = new Phaser.Input(this);
|
||||
this.sound = new Phaser.SoundManager(this);
|
||||
this.physics = new Phaser.Physics(this, this.physicsConfig);
|
||||
this.particles = new Phaser.Particles(this);
|
||||
this.plugins = new Phaser.PluginManager(this);
|
||||
this.net = new Phaser.Net(this);
|
||||
this.debug = new Phaser.Utils.Debug(this);
|
||||
this.scratch = new Phaser.BitmapData(this, '__root', 1024, 1024);
|
||||
|
||||
this.time.boot();
|
||||
this.stage.boot();
|
||||
this.world.boot();
|
||||
this.input.boot();
|
||||
this.sound.boot();
|
||||
this.state.boot();
|
||||
this.debug.boot();
|
||||
|
||||
this.showDebugHeader();
|
||||
|
||||
this.isRunning = true;
|
||||
|
||||
if (this.config && this.config['forceSetTimeOut'])
|
||||
{
|
||||
this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.raf = new Phaser.RequestAnimationFrame(this, false);
|
||||
}
|
||||
|
||||
this.raf.start();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Displays a Phaser version debug header in the console.
|
||||
*
|
||||
* @method Phaser.Game#showDebugHeader
|
||||
* @protected
|
||||
*/
|
||||
showDebugHeader: function () {
|
||||
|
||||
var v = Phaser.VERSION;
|
||||
var r = 'Canvas';
|
||||
var a = 'HTML Audio';
|
||||
var c = 1;
|
||||
|
||||
if (this.renderType === Phaser.WEBGL)
|
||||
{
|
||||
r = 'WebGL';
|
||||
c++;
|
||||
}
|
||||
else if (this.renderType == Phaser.HEADLESS)
|
||||
{
|
||||
r = 'Headless';
|
||||
}
|
||||
|
||||
if (this.device.webAudio)
|
||||
{
|
||||
a = 'WebAudio';
|
||||
c++;
|
||||
}
|
||||
|
||||
if (this.device.chrome)
|
||||
{
|
||||
var args = [
|
||||
'%c %c %c Phaser v' + v + ' - ' + r + ' - ' + a + ' %c %c ' + ' http://phaser.io %c %c ♥%c♥%c♥ ',
|
||||
'background: #0cf300',
|
||||
'background: #00bc17',
|
||||
'color: #ffffff; background: #00711f;',
|
||||
'background: #00bc17',
|
||||
'background: #0cf300',
|
||||
'background: #00bc17'
|
||||
];
|
||||
|
||||
for (var i = 0; i < 3; i++)
|
||||
{
|
||||
if (i < c)
|
||||
{
|
||||
args.push('color: #ff2424; background: #fff');
|
||||
}
|
||||
else
|
||||
{
|
||||
args.push('color: #959595; background: #fff');
|
||||
}
|
||||
}
|
||||
|
||||
console.log.apply(console, args);
|
||||
}
|
||||
else if (window['console'])
|
||||
{
|
||||
console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' - http://phaser.io');
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
|
||||
*
|
||||
* @method Phaser.Game#setUpRenderer
|
||||
* @protected
|
||||
*/
|
||||
setUpRenderer: function () {
|
||||
|
||||
if (this.device.trident)
|
||||
{
|
||||
// Pixi WebGL renderer on IE11 doesn't work correctly at the moment, the pre-multiplied alpha gets all washed out.
|
||||
// So we're forcing canvas for now until this is fixed, sorry. It's got to be better than no game appearing at all, right?
|
||||
this.renderType = Phaser.CANVAS;
|
||||
}
|
||||
|
||||
if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL === false))
|
||||
{
|
||||
if (this.device.canvas)
|
||||
{
|
||||
if (this.renderType === Phaser.AUTO)
|
||||
{
|
||||
this.renderType = Phaser.CANVAS;
|
||||
}
|
||||
|
||||
this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.canvas, this.transparent);
|
||||
this.context = this.renderer.context;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// They requested WebGL, and their browser supports it
|
||||
this.renderType = Phaser.WEBGL;
|
||||
this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.canvas, this.transparent, this.antialias);
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
if (this.renderType !== Phaser.HEADLESS)
|
||||
{
|
||||
this.stage.smoothed = this.antialias;
|
||||
|
||||
Phaser.Canvas.addToDOM(this.canvas, this.parent, true);
|
||||
Phaser.Canvas.setTouchAction(this.canvas);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The core game loop when in a paused state.
|
||||
*
|
||||
* @method Phaser.Game#update
|
||||
* @protected
|
||||
* @param {number} time - The current time as provided by RequestAnimationFrame.
|
||||
*/
|
||||
update: function (time) {
|
||||
|
||||
this.time.update(time);
|
||||
|
||||
if (!this._paused && !this.pendingStep)
|
||||
{
|
||||
if (this.stepping)
|
||||
{
|
||||
this.pendingStep = true;
|
||||
}
|
||||
|
||||
this.debug.preUpdate();
|
||||
this.physics.preUpdate();
|
||||
this.state.preUpdate();
|
||||
this.plugins.preUpdate();
|
||||
this.stage.preUpdate();
|
||||
|
||||
this.state.update();
|
||||
this.stage.update();
|
||||
this.tweens.update();
|
||||
this.sound.update();
|
||||
this.input.update();
|
||||
this.physics.update();
|
||||
this.particles.update();
|
||||
this.plugins.update();
|
||||
|
||||
this.stage.postUpdate();
|
||||
this.plugins.postUpdate();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.state.pauseUpdate();
|
||||
// this.input.update();
|
||||
this.debug.preUpdate();
|
||||
}
|
||||
|
||||
if (this.renderType != Phaser.HEADLESS)
|
||||
{
|
||||
this.renderer.render(this.stage);
|
||||
this.plugins.render();
|
||||
this.state.render();
|
||||
this.plugins.postRender();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
|
||||
* Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
|
||||
*
|
||||
* @method Phaser.Game#enableStep
|
||||
*/
|
||||
enableStep: function () {
|
||||
|
||||
this.stepping = true;
|
||||
this.pendingStep = false;
|
||||
this.stepCount = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Disables core game loop stepping.
|
||||
*
|
||||
* @method Phaser.Game#disableStep
|
||||
*/
|
||||
disableStep: function () {
|
||||
|
||||
this.stepping = false;
|
||||
this.pendingStep = false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
|
||||
* This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
|
||||
*
|
||||
* @method Phaser.Game#step
|
||||
*/
|
||||
step: function () {
|
||||
|
||||
this.pendingStep = false;
|
||||
this.stepCount++;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Nuke the entire game from orbit
|
||||
*
|
||||
* @method Phaser.Game#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.raf.stop();
|
||||
|
||||
this.input.destroy();
|
||||
this.state.destroy();
|
||||
this.physics.destroy();
|
||||
|
||||
this.state = null;
|
||||
this.cache = null;
|
||||
this.input = null;
|
||||
this.load = null;
|
||||
this.sound = null;
|
||||
this.stage = null;
|
||||
this.time = null;
|
||||
this.world = null;
|
||||
this.isBooted = false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the Stage visibility handler.
|
||||
*
|
||||
* @method Phaser.Game#gamePaused
|
||||
* @param {object} event - The DOM event that caused the game to pause, if any.
|
||||
* @protected
|
||||
*/
|
||||
gamePaused: function (event) {
|
||||
|
||||
// If the game is already paused it was done via game code, so don't re-pause it
|
||||
if (!this._paused)
|
||||
{
|
||||
this._paused = true;
|
||||
this.time.gamePaused();
|
||||
this.sound.setMute();
|
||||
this.onPause.dispatch(event);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the Stage visibility handler.
|
||||
*
|
||||
* @method Phaser.Game#gameResumed
|
||||
* @param {object} event - The DOM event that caused the game to pause, if any.
|
||||
* @protected
|
||||
*/
|
||||
gameResumed: function (event) {
|
||||
|
||||
// Game is paused, but wasn't paused via code, so resume it
|
||||
if (this._paused && !this._codePaused)
|
||||
{
|
||||
this._paused = false;
|
||||
this.time.gameResumed();
|
||||
this.input.reset();
|
||||
this.sound.unsetMute();
|
||||
this.onResume.dispatch(event);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the Stage visibility handler.
|
||||
*
|
||||
* @method Phaser.Game#focusLoss
|
||||
* @param {object} event - The DOM event that caused the game to pause, if any.
|
||||
* @protected
|
||||
*/
|
||||
focusLoss: function (event) {
|
||||
|
||||
this.onBlur.dispatch(event);
|
||||
|
||||
this.gamePaused(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the Stage visibility handler.
|
||||
*
|
||||
* @method Phaser.Game#focusGain
|
||||
* @param {object} event - The DOM event that caused the game to pause, if any.
|
||||
* @protected
|
||||
*/
|
||||
focusGain: function (event) {
|
||||
|
||||
this.onFocus.dispatch(event);
|
||||
|
||||
this.gameResumed(event);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Game.prototype.constructor = Phaser.Game;
|
||||
|
||||
/**
|
||||
* The paused state of the Game. A paused game doesn't update any of its subsystems.
|
||||
* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
|
||||
* @name Phaser.Game#paused
|
||||
* @property {boolean} paused - Gets and sets the paused state of the Game.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Game.prototype, "paused", {
|
||||
|
||||
get: function () {
|
||||
return this._paused;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value === true)
|
||||
{
|
||||
if (this._paused === false)
|
||||
{
|
||||
this._paused = true;
|
||||
this._codePaused = true;
|
||||
this.sound.setMute();
|
||||
this.time.gamePaused();
|
||||
this.onPause.dispatch(this);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this._paused)
|
||||
{
|
||||
this._paused = false;
|
||||
this._codePaused = false;
|
||||
this.input.reset();
|
||||
this.sound.unsetMute();
|
||||
this.time.gameResumed();
|
||||
this.onResume.dispatch(this);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* "Deleted code is debugged code." - Jeff Sickel
|
||||
*/
|
||||
1751
src/core/Group.js
Normal file
1751
src/core/Group.js
Normal file
File diff suppressed because it is too large
Load Diff
178
src/core/LinkedList.js
Normal file
178
src/core/LinkedList.js
Normal file
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A basic linked list data structure.
|
||||
*
|
||||
* @class Phaser.LinkedList
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.LinkedList = function () {
|
||||
|
||||
/**
|
||||
* @property {object} next - Next element in the list.
|
||||
* @default
|
||||
*/
|
||||
this.next = null;
|
||||
|
||||
/**
|
||||
* @property {object} prev - Previous element in the list.
|
||||
* @default
|
||||
*/
|
||||
this.prev = null;
|
||||
|
||||
/**
|
||||
* @property {object} first - First element in the list.
|
||||
* @default
|
||||
*/
|
||||
this.first = null;
|
||||
|
||||
/**
|
||||
* @property {object} last - Last element in the list.
|
||||
* @default
|
||||
*/
|
||||
this.last = null;
|
||||
|
||||
/**
|
||||
* @property {number} total - Number of elements in the list.
|
||||
* @default
|
||||
*/
|
||||
this.total = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.LinkedList.prototype = {
|
||||
|
||||
/**
|
||||
* Adds a new element to this linked list.
|
||||
*
|
||||
* @method Phaser.LinkedList#add
|
||||
* @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
|
||||
* @return {object} The child that was added.
|
||||
*/
|
||||
add: function (child) {
|
||||
|
||||
// If the list is empty
|
||||
if (this.total === 0 && this.first === null && this.last === null)
|
||||
{
|
||||
this.first = child;
|
||||
this.last = child;
|
||||
this.next = child;
|
||||
child.prev = this;
|
||||
this.total++;
|
||||
return child;
|
||||
}
|
||||
|
||||
// Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
|
||||
this.last.next = child;
|
||||
|
||||
child.prev = this.last;
|
||||
|
||||
this.last = child;
|
||||
|
||||
this.total++;
|
||||
|
||||
return child;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the first, last, next and previous node pointers in this list.
|
||||
*
|
||||
* @method Phaser.LinkedList#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
this.first = null;
|
||||
this.last = null;
|
||||
this.next = null;
|
||||
this.prev = null;
|
||||
this.total = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes the given element from this linked list if it exists.
|
||||
*
|
||||
* @method Phaser.LinkedList#remove
|
||||
* @param {object} child - The child to be removed from the list.
|
||||
*/
|
||||
remove: function (child) {
|
||||
|
||||
if (this.total === 1)
|
||||
{
|
||||
this.reset();
|
||||
child.next = child.prev = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (child === this.first)
|
||||
{
|
||||
// It was 'first', make 'first' point to first.next
|
||||
this.first = this.first.next;
|
||||
}
|
||||
else if (child === this.last)
|
||||
{
|
||||
// It was 'last', make 'last' point to last.prev
|
||||
this.last = this.last.prev;
|
||||
}
|
||||
|
||||
if (child.prev)
|
||||
{
|
||||
// make child.prev.next point to childs.next instead of child
|
||||
child.prev.next = child.next;
|
||||
}
|
||||
|
||||
if (child.next)
|
||||
{
|
||||
// make child.next.prev point to child.prev instead of child
|
||||
child.next.prev = child.prev;
|
||||
}
|
||||
|
||||
child.next = child.prev = null;
|
||||
|
||||
if (this.first === null )
|
||||
{
|
||||
this.last = null;
|
||||
}
|
||||
|
||||
this.total--;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Calls a function on all members of this list, using the member as the context for the callback.
|
||||
* The function must exist on the member.
|
||||
*
|
||||
* @method Phaser.LinkedList#callAll
|
||||
* @param {function} callback - The function to call.
|
||||
*/
|
||||
callAll: function (callback) {
|
||||
|
||||
if (!this.first || !this.last)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var entity = this.first;
|
||||
|
||||
do
|
||||
{
|
||||
if (entity && entity[callback])
|
||||
{
|
||||
entity[callback].call(entity);
|
||||
}
|
||||
|
||||
entity = entity.next;
|
||||
|
||||
}
|
||||
while(entity != this.last.next);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
|
||||
123
src/core/Plugin.js
Normal file
123
src/core/Plugin.js
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a base Plugin template to use for any Phaser plugin development.
|
||||
*
|
||||
* @class Phaser.Plugin
|
||||
* @classdesc Phaser - Plugin
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager.
|
||||
*/
|
||||
Phaser.Plugin = function (game, parent) {
|
||||
|
||||
if (typeof parent === 'undefined') { parent = null; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null.
|
||||
*/
|
||||
this.parent = parent;
|
||||
|
||||
/**
|
||||
* @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
|
||||
* @default
|
||||
*/
|
||||
this.active = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
|
||||
* @default
|
||||
*/
|
||||
this.visible = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
|
||||
* @default
|
||||
*/
|
||||
this.hasPreUpdate = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
|
||||
* @default
|
||||
*/
|
||||
this.hasUpdate = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
|
||||
* @default
|
||||
*/
|
||||
this.hasPostUpdate = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
|
||||
* @default
|
||||
*/
|
||||
this.hasRender = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
|
||||
* @default
|
||||
*/
|
||||
this.hasPostRender = false;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Plugin.prototype = {
|
||||
|
||||
/**
|
||||
* Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
|
||||
* It is only called if active is set to true.
|
||||
* @method Phaser.Plugin#preUpdate
|
||||
*/
|
||||
preUpdate: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
|
||||
* It is only called if active is set to true.
|
||||
* @method Phaser.Plugin#update
|
||||
*/
|
||||
update: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* Render is called right after the Game Renderer completes, but before the State.render.
|
||||
* It is only called if visible is set to true.
|
||||
* @method Phaser.Plugin#render
|
||||
*/
|
||||
render: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* Post-render is called after the Game Renderer and State.render have run.
|
||||
* It is only called if visible is set to true.
|
||||
* @method Phaser.Plugin#postRender
|
||||
*/
|
||||
postRender: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear down this Plugin and null out references
|
||||
* @method Phaser.Plugin#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.game = null;
|
||||
this.parent = null;
|
||||
this.active = false;
|
||||
this.visible = false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Plugin.prototype.constructor = Phaser.Plugin;
|
||||
288
src/core/PluginManager.js
Normal file
288
src/core/PluginManager.js
Normal file
@@ -0,0 +1,288 @@
|
||||
/* jshint newcap: false */
|
||||
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
|
||||
*
|
||||
* @class Phaser.PluginManager
|
||||
* @classdesc Phaser - PluginManager
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.PluginManager = function(game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {array} plugins - An array of all the plugins being managed by this PluginManager.
|
||||
*/
|
||||
this.plugins = [];
|
||||
|
||||
/**
|
||||
* @property {number} _len - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._len = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _i - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._i = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.PluginManager.prototype = {
|
||||
|
||||
/**
|
||||
* Add a new Plugin into the PluginManager.
|
||||
* The Plugin must have 2 properties: game and parent. Plugin.game is set to ths game reference the PluginManager uses, and parent is set to the PluginManager.
|
||||
*
|
||||
* @method Phaser.PluginManager#add
|
||||
* @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
|
||||
* @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
|
||||
* @return {Phaser.Plugin} The Plugin that was added to the manager.
|
||||
*/
|
||||
add: function (plugin) {
|
||||
|
||||
var args = Array.prototype.splice.call(arguments, 1);
|
||||
var result = false;
|
||||
|
||||
// Prototype?
|
||||
if (typeof plugin === 'function')
|
||||
{
|
||||
plugin = new plugin(this.game, this);
|
||||
}
|
||||
else
|
||||
{
|
||||
plugin.game = this.game;
|
||||
plugin.parent = this;
|
||||
}
|
||||
|
||||
// Check for methods now to avoid having to do this every loop
|
||||
if (typeof plugin['preUpdate'] === 'function')
|
||||
{
|
||||
plugin.hasPreUpdate = true;
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (typeof plugin['update'] === 'function')
|
||||
{
|
||||
plugin.hasUpdate = true;
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (typeof plugin['postUpdate'] === 'function')
|
||||
{
|
||||
plugin.hasPostUpdate = true;
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (typeof plugin['render'] === 'function')
|
||||
{
|
||||
plugin.hasRender = true;
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (typeof plugin['postRender'] === 'function')
|
||||
{
|
||||
plugin.hasPostRender = true;
|
||||
result = true;
|
||||
}
|
||||
|
||||
// The plugin must have at least one of the above functions to be added to the PluginManager.
|
||||
if (result)
|
||||
{
|
||||
if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
|
||||
{
|
||||
plugin.active = true;
|
||||
}
|
||||
|
||||
if (plugin.hasRender || plugin.hasPostRender)
|
||||
{
|
||||
plugin.visible = true;
|
||||
}
|
||||
|
||||
this._len = this.plugins.push(plugin);
|
||||
|
||||
// Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
|
||||
if (typeof plugin['init'] === 'function')
|
||||
{
|
||||
plugin.init.apply(plugin, args);
|
||||
}
|
||||
|
||||
return plugin;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
|
||||
*
|
||||
* @method Phaser.PluginManager#remove
|
||||
* @param {Phaser.Plugin} plugin - The plugin to be removed.
|
||||
*/
|
||||
remove: function (plugin) {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i] === plugin)
|
||||
{
|
||||
plugin.destroy();
|
||||
this.plugins.splice(this._i, 1);
|
||||
this._len--;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
|
||||
*
|
||||
* @method Phaser.PluginManager#removeAll
|
||||
*/
|
||||
removeAll: function() {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
this.plugins[this._i].destroy();
|
||||
}
|
||||
|
||||
this.plugins.length = 0;
|
||||
this._len = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
|
||||
* It only calls plugins who have active=true.
|
||||
*
|
||||
* @method Phaser.PluginManager#preUpdate
|
||||
*/
|
||||
preUpdate: function () {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
|
||||
{
|
||||
this.plugins[this._i].preUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
|
||||
* It only calls plugins who have active=true.
|
||||
*
|
||||
* @method Phaser.PluginManager#update
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
|
||||
{
|
||||
this.plugins[this._i].update();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* PostUpdate is the last thing to be called before the world render.
|
||||
* In particular, it is called after the world postUpdate, which means the camera has been adjusted.
|
||||
* It only calls plugins who have active=true.
|
||||
*
|
||||
* @method Phaser.PluginManager#postUpdate
|
||||
*/
|
||||
postUpdate: function () {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
|
||||
{
|
||||
this.plugins[this._i].postUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Render is called right after the Game Renderer completes, but before the State.render.
|
||||
* It only calls plugins who have visible=true.
|
||||
*
|
||||
* @method Phaser.PluginManager#render
|
||||
*/
|
||||
render: function () {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
|
||||
{
|
||||
this.plugins[this._i].render();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Post-render is called after the Game Renderer and State.render have run.
|
||||
* It only calls plugins who have visible=true.
|
||||
*
|
||||
* @method Phaser.PluginManager#postRender
|
||||
*/
|
||||
postRender: function () {
|
||||
|
||||
this._i = this._len;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
|
||||
{
|
||||
this.plugins[this._i].postRender();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear down this PluginManager, calls destroy on every plugin and nulls out references.
|
||||
*
|
||||
* @method Phaser.PluginManager#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.removeAll();
|
||||
|
||||
this.game = null;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
|
||||
806
src/core/ScaleManager.js
Normal file
806
src/core/ScaleManager.js
Normal file
@@ -0,0 +1,806 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The ScaleManager object is responsible for helping you manage the scaling, resizing and alignment of your game within the browser.
|
||||
*
|
||||
* @class Phaser.ScaleManager
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} width - The native width of the game.
|
||||
* @param {number} height - The native height of the game.
|
||||
*/
|
||||
Phaser.ScaleManager = function (game, width, height) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {number} width - Width of the stage after calculation.
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - Height of the stage after calculation.
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels).
|
||||
*/
|
||||
this.minWidth = null;
|
||||
|
||||
/**
|
||||
* @property {number} maxWidth - Maximum width the canvas should be scaled to (in pixels). If null it will scale to whatever width the browser can handle.
|
||||
*/
|
||||
this.maxWidth = null;
|
||||
|
||||
/**
|
||||
* @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels).
|
||||
*/
|
||||
this.minHeight = null;
|
||||
|
||||
/**
|
||||
* @property {number} maxHeight - Maximum height the canvas should be scaled to (in pixels). If null it will scale to whatever height the browser can handle.
|
||||
*/
|
||||
this.maxHeight = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage
|
||||
* @default
|
||||
*/
|
||||
this.forceLandscape = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage
|
||||
* @default
|
||||
*/
|
||||
this.forcePortrait = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true.
|
||||
* @default
|
||||
*/
|
||||
this.incorrectOrientation = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true.
|
||||
* It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
|
||||
* It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
|
||||
* @default
|
||||
*/
|
||||
this.pageAlignHorizontally = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true.
|
||||
* It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing.
|
||||
* It doesn't care about any other DOM element that may be on the page, it literally just sets the margin.
|
||||
* @default
|
||||
*/
|
||||
this.pageAlignVertically = false;
|
||||
|
||||
/**
|
||||
* @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser.
|
||||
* @default
|
||||
*/
|
||||
this.maxIterations = 5;
|
||||
|
||||
/**
|
||||
* @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation.
|
||||
*/
|
||||
this.orientationSprite = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation.
|
||||
*/
|
||||
this.enterLandscape = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation.
|
||||
*/
|
||||
this.enterPortrait = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation.
|
||||
*/
|
||||
this.enterIncorrectOrientation = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation.
|
||||
*/
|
||||
this.leaveIncorrectOrientation = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} hasResized - The event that is dispatched when the game scale changes.
|
||||
*/
|
||||
this.hasResized = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* This is the DOM element that will have the Full Screen mode called on it. It defaults to the game canvas, but can be retargetted to any valid DOM element.
|
||||
* If you adjust this property it's up to you to see it has the correct CSS applied, and that you have contained the game canvas correctly.
|
||||
* Note that if you use a scale property of EXACT_FIT then fullScreenTarget will have its width and height style set to 100%.
|
||||
* @property {any} fullScreenTarget
|
||||
*/
|
||||
this.fullScreenTarget = this.game.canvas;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} enterFullScreen - The event that is dispatched when the browser enters full screen mode (if it supports the FullScreen API).
|
||||
*/
|
||||
this.enterFullScreen = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} leaveFullScreen - The event that is dispatched when the browser leaves full screen mode (if it supports the FullScreen API).
|
||||
*/
|
||||
this.leaveFullScreen = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {number} orientation - The orientation value of the game (as defined by window.orientation if set). 90 = landscape. 0 = portrait.
|
||||
*/
|
||||
this.orientation = 0;
|
||||
|
||||
if (window['orientation'])
|
||||
{
|
||||
this.orientation = window['orientation'];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (window.outerWidth > window.outerHeight)
|
||||
{
|
||||
this.orientation = 90;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
|
||||
* @readonly
|
||||
*/
|
||||
this.scaleFactor = new Phaser.Point(1, 1);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} scaleFactorInversed - The inversed scale factor. The displayed dimensions divided by the game dimensions.
|
||||
* @readonly
|
||||
*/
|
||||
this.scaleFactorInversed = new Phaser.Point(1, 1);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} margin - If the game canvas is set to align by adjusting the margin, the margin calculation values are stored in this Point.
|
||||
* @readonly
|
||||
*/
|
||||
this.margin = new Phaser.Point(0, 0);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Rectangle} bounds - The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height.
|
||||
* @readonly
|
||||
*/
|
||||
this.bounds = new Phaser.Rectangle(0, 0, width, height);
|
||||
|
||||
/**
|
||||
* @property {number} aspectRatio - The aspect ratio of the scaled game.
|
||||
* @readonly
|
||||
*/
|
||||
this.aspectRatio = 0;
|
||||
|
||||
/**
|
||||
* @property {number} sourceAspectRatio - The aspect ratio (width / height) of the original game dimensions.
|
||||
* @readonly
|
||||
*/
|
||||
this.sourceAspectRatio = width / height;
|
||||
|
||||
/**
|
||||
* @property {any} event- The native browser events from full screen API changes.
|
||||
*/
|
||||
this.event = null;
|
||||
|
||||
/**
|
||||
* @property {number} scaleMode - The current scaleMode.
|
||||
*/
|
||||
this.scaleMode = Phaser.ScaleManager.NO_SCALE;
|
||||
|
||||
/*
|
||||
* @property {number} fullScreenScaleMode - Scale mode to be used in fullScreen
|
||||
*/
|
||||
this.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
|
||||
|
||||
/**
|
||||
* @property {number} _startHeight - Internal cache var. Stage height when starting the game.
|
||||
* @private
|
||||
*/
|
||||
this._startHeight = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _width - Cached stage width for full screen mode.
|
||||
* @private
|
||||
*/
|
||||
this._width = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _height - Cached stage height for full screen mode.
|
||||
* @private
|
||||
*/
|
||||
this._height = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _check - Cached size interval var.
|
||||
* @private
|
||||
*/
|
||||
this._check = null;
|
||||
|
||||
var _this = this;
|
||||
|
||||
window.addEventListener('orientationchange', function (event) {
|
||||
return _this.checkOrientation(event);
|
||||
}, false);
|
||||
|
||||
window.addEventListener('resize', function (event) {
|
||||
return _this.checkResize(event);
|
||||
}, false);
|
||||
|
||||
document.addEventListener('webkitfullscreenchange', function (event) {
|
||||
return _this.fullScreenChange(event);
|
||||
}, false);
|
||||
|
||||
document.addEventListener('mozfullscreenchange', function (event) {
|
||||
return _this.fullScreenChange(event);
|
||||
}, false);
|
||||
|
||||
document.addEventListener('fullscreenchange', function (event) {
|
||||
return _this.fullScreenChange(event);
|
||||
}, false);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.ScaleManager.EXACT_FIT = 0;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.ScaleManager.NO_SCALE = 1;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.ScaleManager.SHOW_ALL = 2;
|
||||
|
||||
Phaser.ScaleManager.prototype = {
|
||||
|
||||
/**
|
||||
* Tries to enter the browser into full screen mode.
|
||||
* Please note that this needs to be supported by the web browser and isn't the same thing as setting your game to fill the browser.
|
||||
* @method Phaser.ScaleManager#startFullScreen
|
||||
* @param {boolean} antialias - You can toggle the anti-alias feature of the canvas before jumping in to full screen (false = retain pixel art, true = smooth art)
|
||||
*/
|
||||
startFullScreen: function (antialias) {
|
||||
|
||||
if (this.isFullScreen || !this.game.device.fullscreen)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof antialias !== 'undefined' && this.game.renderType === Phaser.CANVAS)
|
||||
{
|
||||
this.game.stage.smoothed = antialias;
|
||||
}
|
||||
|
||||
this._width = this.width;
|
||||
this._height = this.height;
|
||||
|
||||
if (this.game.device.fullscreenKeyboard)
|
||||
{
|
||||
this.fullScreenTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.fullScreenTarget[this.game.device.requestFullscreen]();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops full screen mode if the browser is in it.
|
||||
* @method Phaser.ScaleManager#stopFullScreen
|
||||
*/
|
||||
stopFullScreen: function () {
|
||||
|
||||
this.fullScreenTarget[this.game.device.cancelFullscreen]();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called automatically when the browser enters of leaves full screen mode.
|
||||
* @method Phaser.ScaleManager#fullScreenChange
|
||||
* @param {Event} event - The fullscreenchange event
|
||||
* @protected
|
||||
*/
|
||||
fullScreenChange: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.isFullScreen)
|
||||
{
|
||||
if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
|
||||
{
|
||||
this.fullScreenTarget.style['width'] = '100%';
|
||||
this.fullScreenTarget.style['height'] = '100%';
|
||||
|
||||
this.width = window.outerWidth;
|
||||
this.height = window.outerHeight;
|
||||
|
||||
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
|
||||
|
||||
this.aspectRatio = this.width / this.height;
|
||||
this.scaleFactor.x = this.game.width / this.width;
|
||||
this.scaleFactor.y = this.game.height / this.height;
|
||||
|
||||
this.checkResize();
|
||||
}
|
||||
else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
|
||||
{
|
||||
this.setShowAll();
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
this.enterFullScreen.dispatch(this.width, this.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.fullScreenTarget.style['width'] = this.game.width + 'px';
|
||||
this.fullScreenTarget.style['height'] = this.game.height + 'px';
|
||||
|
||||
this.width = this._width;
|
||||
this.height = this._height;
|
||||
|
||||
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
|
||||
|
||||
this.aspectRatio = this.width / this.height;
|
||||
this.scaleFactor.x = this.game.width / this.width;
|
||||
this.scaleFactor.y = this.game.height / this.height;
|
||||
|
||||
this.leaveFullScreen.dispatch(this.width, this.height);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If you need your game to run in only one orientation you can force that to happen.
|
||||
* The optional orientationImage is displayed when the game is in the incorrect orientation.
|
||||
* @method Phaser.ScaleManager#forceOrientation
|
||||
* @param {boolean} forceLandscape - true if the game should run in landscape mode only.
|
||||
* @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
|
||||
* @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation.
|
||||
*/
|
||||
forceOrientation: function (forceLandscape, forcePortrait, orientationImage) {
|
||||
|
||||
if (typeof forcePortrait === 'undefined') { forcePortrait = false; }
|
||||
|
||||
this.forceLandscape = forceLandscape;
|
||||
this.forcePortrait = forcePortrait;
|
||||
|
||||
if (typeof orientationImage !== 'undefined')
|
||||
{
|
||||
if (orientationImage === null || this.game.cache.checkImageKey(orientationImage) === false)
|
||||
{
|
||||
orientationImage = '__default';
|
||||
}
|
||||
|
||||
this.orientationSprite = new Phaser.Image(this.game, this.game.width / 2, this.game.height / 2, PIXI.TextureCache[orientationImage]);
|
||||
this.orientationSprite.anchor.set(0.5);
|
||||
|
||||
this.checkOrientationState();
|
||||
|
||||
if (this.incorrectOrientation)
|
||||
{
|
||||
this.orientationSprite.visible = true;
|
||||
this.game.world.visible = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.orientationSprite.visible = false;
|
||||
this.game.world.visible = true;
|
||||
}
|
||||
|
||||
this.game.stage.addChild(this.orientationSprite);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set)
|
||||
* @method Phaser.ScaleManager#checkOrientationState
|
||||
*/
|
||||
checkOrientationState: function () {
|
||||
|
||||
// They are in the wrong orientation
|
||||
if (this.incorrectOrientation)
|
||||
{
|
||||
if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth))
|
||||
{
|
||||
// Back to normal
|
||||
this.incorrectOrientation = false;
|
||||
this.leaveIncorrectOrientation.dispatch();
|
||||
|
||||
if (this.orientationSprite)
|
||||
{
|
||||
this.orientationSprite.visible = false;
|
||||
this.game.world.visible = true;
|
||||
}
|
||||
|
||||
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
|
||||
{
|
||||
this.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth))
|
||||
{
|
||||
// Show orientation screen
|
||||
this.incorrectOrientation = true;
|
||||
this.enterIncorrectOrientation.dispatch();
|
||||
|
||||
if (this.orientationSprite && this.orientationSprite.visible === false)
|
||||
{
|
||||
this.orientationSprite.visible = true;
|
||||
this.game.world.visible = false;
|
||||
}
|
||||
|
||||
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
|
||||
{
|
||||
this.refresh();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle window.orientationchange events
|
||||
* @method Phaser.ScaleManager#checkOrientation
|
||||
* @param {Event} event - The orientationchange event data.
|
||||
*/
|
||||
checkOrientation: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
this.orientation = window['orientation'];
|
||||
|
||||
if (this.isLandscape)
|
||||
{
|
||||
this.enterLandscape.dispatch(this.orientation, true, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.enterPortrait.dispatch(this.orientation, false, true);
|
||||
}
|
||||
|
||||
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
|
||||
{
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle window.resize events
|
||||
* @method Phaser.ScaleManager#checkResize
|
||||
* @param {Event} event - The resize event data.
|
||||
*/
|
||||
checkResize: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (window.outerWidth > window.outerHeight)
|
||||
{
|
||||
this.orientation = 90;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.orientation = 0;
|
||||
}
|
||||
|
||||
if (this.isLandscape)
|
||||
{
|
||||
this.enterLandscape.dispatch(this.orientation, true, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.enterPortrait.dispatch(this.orientation, false, true);
|
||||
}
|
||||
|
||||
if (this.scaleMode !== Phaser.ScaleManager.NO_SCALE)
|
||||
{
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
this.checkOrientationState();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-calculate scale mode and update screen size.
|
||||
* @method Phaser.ScaleManager#refresh
|
||||
*/
|
||||
refresh: function () {
|
||||
|
||||
// We can't do anything about the status bars in iPads, web apps or desktops
|
||||
if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
|
||||
{
|
||||
// TODO - Test this
|
||||
// this._startHeight = window.innerHeight;
|
||||
|
||||
if (this.game.device.android && !this.game.device.chrome)
|
||||
{
|
||||
window.scrollTo(0, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (this._check === null && this.maxIterations > 0)
|
||||
{
|
||||
this._iterations = this.maxIterations;
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._check = window.setInterval(function () {
|
||||
return _this.setScreenSize();
|
||||
}, 10);
|
||||
|
||||
this.setScreenSize();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Set screen size automatically based on the scaleMode.
|
||||
* @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions.
|
||||
*/
|
||||
setScreenSize: function (force) {
|
||||
|
||||
if (typeof force === 'undefined')
|
||||
{
|
||||
force = false;
|
||||
}
|
||||
|
||||
if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
|
||||
{
|
||||
if (this.game.device.android && !this.game.device.chrome)
|
||||
{
|
||||
window.scrollTo(0, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
this._iterations--;
|
||||
|
||||
if (force || window.innerHeight > this._startHeight || this._iterations < 0)
|
||||
{
|
||||
// Set minimum height of content to new window height
|
||||
document.documentElement['style'].minHeight = window.innerHeight + 'px';
|
||||
|
||||
if (this.incorrectOrientation)
|
||||
{
|
||||
this.setMaximum();
|
||||
}
|
||||
else if (!this.isFullScreen)
|
||||
{
|
||||
if (this.scaleMode === Phaser.ScaleManager.EXACT_FIT)
|
||||
{
|
||||
this.setExactFit();
|
||||
}
|
||||
else if (this.scaleMode === Phaser.ScaleManager.SHOW_ALL)
|
||||
{
|
||||
this.setShowAll();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
|
||||
{
|
||||
this.setExactFit();
|
||||
}
|
||||
else if (this.fullScreenScaleMode === Phaser.ScaleManager.SHOW_ALL)
|
||||
{
|
||||
this.setShowAll();
|
||||
}
|
||||
}
|
||||
|
||||
this.setSize();
|
||||
clearInterval(this._check);
|
||||
this._check = null;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height.
|
||||
* @method Phaser.ScaleManager#setSize
|
||||
*/
|
||||
setSize: function () {
|
||||
|
||||
if (!this.incorrectOrientation)
|
||||
{
|
||||
if (this.maxWidth && this.width > this.maxWidth)
|
||||
{
|
||||
this.width = this.maxWidth;
|
||||
}
|
||||
|
||||
if (this.maxHeight && this.height > this.maxHeight)
|
||||
{
|
||||
this.height = this.maxHeight;
|
||||
}
|
||||
|
||||
if (this.minWidth && this.width < this.minWidth)
|
||||
{
|
||||
this.width = this.minWidth;
|
||||
}
|
||||
|
||||
if (this.minHeight && this.height < this.minHeight)
|
||||
{
|
||||
this.height = this.minHeight;
|
||||
}
|
||||
}
|
||||
|
||||
this.game.canvas.style.width = this.width + 'px';
|
||||
this.game.canvas.style.height = this.height + 'px';
|
||||
|
||||
this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height);
|
||||
|
||||
if (this.pageAlignHorizontally)
|
||||
{
|
||||
if (this.width < window.innerWidth && !this.incorrectOrientation)
|
||||
{
|
||||
this.margin.x = Math.round((window.innerWidth - this.width) / 2);
|
||||
this.game.canvas.style.marginLeft = this.margin.x + 'px';
|
||||
}
|
||||
else
|
||||
{
|
||||
this.margin.x = 0;
|
||||
this.game.canvas.style.marginLeft = '0px';
|
||||
}
|
||||
}
|
||||
|
||||
if (this.pageAlignVertically)
|
||||
{
|
||||
if (this.height < window.innerHeight && !this.incorrectOrientation)
|
||||
{
|
||||
this.margin.y = Math.round((window.innerHeight - this.height) / 2);
|
||||
this.game.canvas.style.marginTop = this.margin.y + 'px';
|
||||
}
|
||||
else
|
||||
{
|
||||
this.margin.y = 0;
|
||||
this.game.canvas.style.marginTop = '0px';
|
||||
}
|
||||
}
|
||||
|
||||
Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset);
|
||||
|
||||
this.bounds.setTo(this.game.stage.offset.x, this.game.stage.offset.y, this.width, this.height);
|
||||
|
||||
this.aspectRatio = this.width / this.height;
|
||||
|
||||
this.scaleFactor.x = this.game.width / this.width;
|
||||
this.scaleFactor.y = this.game.height / this.height;
|
||||
|
||||
this.scaleFactorInversed.x = this.width / this.game.width;
|
||||
this.scaleFactorInversed.y = this.height / this.game.height;
|
||||
|
||||
this.hasResized.dispatch(this.width, this.height);
|
||||
|
||||
this.checkOrientationState();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight
|
||||
* @method Phaser.ScaleManager#setMaximum
|
||||
*/
|
||||
setMaximum: function () {
|
||||
|
||||
this.width = window.innerWidth;
|
||||
this.height = window.innerHeight;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Calculates the multiplier needed to scale the game proportionally.
|
||||
* @method Phaser.ScaleManager#setShowAll
|
||||
*/
|
||||
setShowAll: function () {
|
||||
|
||||
var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width));
|
||||
|
||||
this.width = Math.round(this.game.width * multiplier);
|
||||
this.height = Math.round(this.game.height * multiplier);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the width and height values of the canvas, no larger than the maxWidth/Height.
|
||||
* @method Phaser.ScaleManager#setExactFit
|
||||
*/
|
||||
setExactFit: function () {
|
||||
|
||||
var availableWidth = window.innerWidth;
|
||||
var availableHeight = window.innerHeight;
|
||||
|
||||
if (this.maxWidth && availableWidth > this.maxWidth)
|
||||
{
|
||||
this.width = this.maxWidth;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.width = availableWidth;
|
||||
}
|
||||
|
||||
if (this.maxHeight && availableHeight > this.maxHeight)
|
||||
{
|
||||
this.height = this.maxHeight;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.height = availableHeight;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
|
||||
|
||||
/**
|
||||
* @name Phaser.ScaleManager#isFullScreen
|
||||
* @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement']);
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.ScaleManager#isPortrait
|
||||
* @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
|
||||
|
||||
get: function () {
|
||||
return (this.orientation === 0 || this.orientation === 180);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.ScaleManager#isLandscape
|
||||
* @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
|
||||
|
||||
get: function () {
|
||||
return (this.orientation === 90 || this.orientation === -90);
|
||||
}
|
||||
|
||||
});
|
||||
304
src/core/Signal.js
Normal file
304
src/core/Signal.js
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Signal
|
||||
* @classdesc A Signal is used for object communication via a custom broadcaster instead of Events.
|
||||
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.Signal = function () {
|
||||
|
||||
/**
|
||||
* @property {Array.<Phaser.SignalBinding>} _bindings - Internal variable.
|
||||
* @private
|
||||
*/
|
||||
this._bindings = [];
|
||||
|
||||
/**
|
||||
* @property {any} _prevParams - Internal variable.
|
||||
* @private
|
||||
*/
|
||||
this._prevParams = null;
|
||||
|
||||
// enforce dispatch to aways work on same context (#47)
|
||||
var self = this;
|
||||
|
||||
/**
|
||||
* @property {function} dispatch - The dispatch function is what sends the Signal out.
|
||||
*/
|
||||
this.dispatch = function(){
|
||||
Phaser.Signal.prototype.dispatch.apply(self, arguments);
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
Phaser.Signal.prototype = {
|
||||
|
||||
/**
|
||||
* If Signal should keep record of previously dispatched parameters and
|
||||
* automatically execute listener during `add()`/`addOnce()` if Signal was
|
||||
* already dispatched before.
|
||||
* @property {boolean} memorize
|
||||
*/
|
||||
memorize: false,
|
||||
|
||||
/**
|
||||
* @property {boolean} _shouldPropagate
|
||||
* @private
|
||||
*/
|
||||
_shouldPropagate: true,
|
||||
|
||||
/**
|
||||
* If Signal is active and should broadcast events.
|
||||
* <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
|
||||
* @property {boolean} active
|
||||
* @default
|
||||
*/
|
||||
active: true,
|
||||
|
||||
/**
|
||||
* @method Phaser.Signal#validateListener
|
||||
* @param {function} listener - Signal handler function.
|
||||
* @param {string} fnName - Function name.
|
||||
* @private
|
||||
*/
|
||||
validateListener: function (listener, fnName) {
|
||||
if (typeof listener !== 'function') {
|
||||
throw new Error('listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Signal#_registerListener
|
||||
* @param {function} listener - Signal handler function.
|
||||
* @param {boolean} isOnce - Description.
|
||||
* @param {object} [listenerContext] - Description.
|
||||
* @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
|
||||
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
|
||||
* @private
|
||||
*/
|
||||
_registerListener: function (listener, isOnce, listenerContext, priority) {
|
||||
|
||||
var prevIndex = this._indexOfListener(listener, listenerContext),
|
||||
binding;
|
||||
|
||||
if (prevIndex !== -1) {
|
||||
binding = this._bindings[prevIndex];
|
||||
if (binding.isOnce() !== isOnce) {
|
||||
throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
|
||||
}
|
||||
} else {
|
||||
binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority);
|
||||
this._addBinding(binding);
|
||||
}
|
||||
|
||||
if (this.memorize && this._prevParams) {
|
||||
binding.execute(this._prevParams);
|
||||
}
|
||||
|
||||
return binding;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Signal#_addBinding
|
||||
* @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
|
||||
* @private
|
||||
*/
|
||||
_addBinding: function (binding) {
|
||||
//simplified insertion sort
|
||||
var n = this._bindings.length;
|
||||
do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
|
||||
this._bindings.splice(n + 1, 0, binding);
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Signal#_indexOfListener
|
||||
* @param {function} listener - Signal handler function.
|
||||
* @return {number} Description.
|
||||
* @private
|
||||
*/
|
||||
_indexOfListener: function (listener, context) {
|
||||
var n = this._bindings.length,
|
||||
cur;
|
||||
while (n--) {
|
||||
cur = this._bindings[n];
|
||||
if (cur._listener === listener && cur.context === context) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if listener was attached to Signal.
|
||||
*
|
||||
* @method Phaser.Signal#has
|
||||
* @param {Function} listener - Signal handler function.
|
||||
* @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
|
||||
* @return {boolean} If Signal has the specified listener.
|
||||
*/
|
||||
has: function (listener, context) {
|
||||
return this._indexOfListener(listener, context) !== -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Add a listener to the signal.
|
||||
*
|
||||
* @method Phaser.Signal#add
|
||||
* @param {function} listener - Signal handler function.
|
||||
* @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
|
||||
* @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
|
||||
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
|
||||
*/
|
||||
add: function (listener, listenerContext, priority) {
|
||||
this.validateListener(listener, 'add');
|
||||
return this._registerListener(listener, false, listenerContext, priority);
|
||||
},
|
||||
|
||||
/**
|
||||
* Add listener to the signal that should be removed after first execution (will be executed only once).
|
||||
*
|
||||
* @method Phaser.Signal#addOnce
|
||||
* @param {function} listener Signal handler function.
|
||||
* @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
|
||||
* @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
|
||||
* @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
|
||||
*/
|
||||
addOnce: function (listener, listenerContext, priority) {
|
||||
this.validateListener(listener, 'addOnce');
|
||||
return this._registerListener(listener, true, listenerContext, priority);
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove a single listener from the dispatch queue.
|
||||
*
|
||||
* @method Phaser.Signal#remove
|
||||
* @param {function} listener Handler function that should be removed.
|
||||
* @param {object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
|
||||
* @return {function} Listener handler function.
|
||||
*/
|
||||
remove: function (listener, context) {
|
||||
|
||||
this.validateListener(listener, 'remove');
|
||||
|
||||
var i = this._indexOfListener(listener, context);
|
||||
|
||||
if (i !== -1)
|
||||
{
|
||||
this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
|
||||
this._bindings.splice(i, 1);
|
||||
}
|
||||
|
||||
return listener;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all listeners from the Signal.
|
||||
*
|
||||
* @method Phaser.Signal#removeAll
|
||||
*/
|
||||
removeAll: function () {
|
||||
var n = this._bindings.length;
|
||||
while (n--) {
|
||||
this._bindings[n]._destroy();
|
||||
}
|
||||
this._bindings.length = 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets the total number of listeneres attached to ths Signal.
|
||||
*
|
||||
* @method Phaser.Signal#getNumListeners
|
||||
* @return {number} Number of listeners attached to the Signal.
|
||||
*/
|
||||
getNumListeners: function () {
|
||||
return this._bindings.length;
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop propagation of the event, blocking the dispatch to next listeners on the queue.
|
||||
* IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.
|
||||
* @see Signal.prototype.disable
|
||||
*
|
||||
* @method Phaser.Signal#halt
|
||||
*/
|
||||
halt: function () {
|
||||
this._shouldPropagate = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Dispatch/Broadcast Signal to all listeners added to the queue.
|
||||
*
|
||||
* @method Phaser.Signal#dispatch
|
||||
* @param {any} [params] - Parameters that should be passed to each handler.
|
||||
*/
|
||||
dispatch: function () {
|
||||
|
||||
if (!this.active)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var paramsArr = Array.prototype.slice.call(arguments);
|
||||
var n = this._bindings.length;
|
||||
var bindings;
|
||||
|
||||
if (this.memorize)
|
||||
{
|
||||
this._prevParams = paramsArr;
|
||||
}
|
||||
|
||||
if (!n)
|
||||
{
|
||||
// Should come after memorize
|
||||
return;
|
||||
}
|
||||
|
||||
bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
|
||||
this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
|
||||
|
||||
//execute all callbacks until end of the list or until a callback returns `false` or stops propagation
|
||||
//reverse loop since listeners with higher priority will be added at the end of the list
|
||||
do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Forget memorized arguments.
|
||||
* @see Signal.memorize
|
||||
*
|
||||
* @method Phaser.Signal#forget
|
||||
*/
|
||||
forget: function(){
|
||||
this._prevParams = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
|
||||
* IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.
|
||||
*
|
||||
* @method Phaser.Signal#dispose
|
||||
*/
|
||||
dispose: function () {
|
||||
this.removeAll();
|
||||
delete this._bindings;
|
||||
delete this._prevParams;
|
||||
},
|
||||
|
||||
/**
|
||||
*
|
||||
* @method Phaser.Signal#toString
|
||||
* @return {string} String representation of the object.
|
||||
*/
|
||||
toString: function () {
|
||||
return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Signal.prototype.constructor = Phaser.Signal;
|
||||
159
src/core/SignalBinding.js
Normal file
159
src/core/SignalBinding.js
Normal file
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.SignalBinding
|
||||
* @classdesc Object that represents a binding between a Signal and a listener function.
|
||||
* This is an internal constructor and shouldn't be called by regular users.
|
||||
* Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
|
||||
*
|
||||
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
|
||||
* @constructor
|
||||
* @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
|
||||
* @param {function} listener - Handler function bound to the signal.
|
||||
* @param {boolean} isOnce - If binding should be executed just once.
|
||||
* @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
|
||||
* @param {number} [priority] - The priority level of the event listener. (default = 0).
|
||||
*/
|
||||
Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} _listener - Handler function bound to the signal.
|
||||
* @private
|
||||
*/
|
||||
this._listener = listener;
|
||||
|
||||
/**
|
||||
* @property {boolean} _isOnce - If binding should be executed just once.
|
||||
* @private
|
||||
*/
|
||||
this._isOnce = isOnce;
|
||||
|
||||
/**
|
||||
* @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
|
||||
*/
|
||||
this.context = listenerContext;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
|
||||
* @private
|
||||
*/
|
||||
this._signal = signal;
|
||||
|
||||
/**
|
||||
* @property {number} _priority - Listener priority.
|
||||
* @private
|
||||
*/
|
||||
this._priority = priority || 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.SignalBinding.prototype = {
|
||||
|
||||
/**
|
||||
* If binding is active and should be executed.
|
||||
* @property {boolean} active
|
||||
* @default
|
||||
*/
|
||||
active: true,
|
||||
|
||||
/**
|
||||
* Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
|
||||
* @property {array|null} params
|
||||
* @default
|
||||
*/
|
||||
params: null,
|
||||
|
||||
/**
|
||||
* Call listener passing arbitrary parameters.
|
||||
* If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
|
||||
* @method Phaser.SignalBinding#execute
|
||||
* @param {array} [paramsArr] - Array of parameters that should be passed to the listener.
|
||||
* @return {any} Value returned by the listener.
|
||||
*/
|
||||
execute: function(paramsArr) {
|
||||
|
||||
var handlerReturn, params;
|
||||
|
||||
if (this.active && !!this._listener)
|
||||
{
|
||||
params = this.params ? this.params.concat(paramsArr) : paramsArr;
|
||||
handlerReturn = this._listener.apply(this.context, params);
|
||||
|
||||
if (this._isOnce)
|
||||
{
|
||||
this.detach();
|
||||
}
|
||||
}
|
||||
|
||||
return handlerReturn;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Detach binding from signal.
|
||||
* alias to: @see mySignal.remove(myBinding.getListener());
|
||||
* @method Phaser.SignalBinding#detach
|
||||
* @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
|
||||
*/
|
||||
detach: function () {
|
||||
return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#isBound
|
||||
* @return {boolean} True if binding is still bound to the signal and has a listener.
|
||||
*/
|
||||
isBound: function () {
|
||||
return (!!this._signal && !!this._listener);
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#isOnce
|
||||
* @return {boolean} If SignalBinding will only be executed once.
|
||||
*/
|
||||
isOnce: function () {
|
||||
return this._isOnce;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#getListener
|
||||
* @return {Function} Handler function bound to the signal.
|
||||
*/
|
||||
getListener: function () {
|
||||
return this._listener;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#getSignal
|
||||
* @return {Signal} Signal that listener is currently bound to.
|
||||
*/
|
||||
getSignal: function () {
|
||||
return this._signal;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#_destroy
|
||||
* Delete instance properties
|
||||
* @private
|
||||
*/
|
||||
_destroy: function () {
|
||||
delete this._signal;
|
||||
delete this._listener;
|
||||
delete this.context;
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.SignalBinding#toString
|
||||
* @return {string} String representation of the object.
|
||||
*/
|
||||
toString: function () {
|
||||
return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
|
||||
421
src/core/Stage.js
Normal file
421
src/core/Stage.js
Normal file
@@ -0,0 +1,421 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Stage controls the canvas on which everything is displayed. It handles display within the browser,
|
||||
* focus handling, game resizing, scaling and the pause, boot and orientation screens.
|
||||
*
|
||||
* @class Phaser.Stage
|
||||
* @extends PIXI.Stage
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Game reference to the currently running game.
|
||||
* @param {number} width - Width of the canvas element.
|
||||
* @param {number} height - Height of the canvas element.
|
||||
*/
|
||||
Phaser.Stage = function (game, width, height) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} offset - Holds the offset coordinates of the Game.canvas from the top-left of the browser window (used by Input and other classes)
|
||||
*/
|
||||
this.offset = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Rectangle} bounds - The bounds of the Stage. Typically x/y = Stage.offset.x/y and the width/height match the game width and height.
|
||||
*/
|
||||
this.bounds = new Phaser.Rectangle(0, 0, width, height);
|
||||
|
||||
PIXI.Stage.call(this, 0x000000, false);
|
||||
|
||||
/**
|
||||
* @property {string} name - The name of this object.
|
||||
* @default
|
||||
*/
|
||||
this.name = '_stage_root';
|
||||
|
||||
/**
|
||||
* @property {boolean} interactive - Pixi level var, ignored by Phaser.
|
||||
* @default
|
||||
* @private
|
||||
*/
|
||||
this.interactive = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} disableVisibilityChange - By default if the browser tab loses focus the game will pause. You can stop that behaviour by setting this property to true.
|
||||
* @default
|
||||
*/
|
||||
this.disableVisibilityChange = false;
|
||||
|
||||
/**
|
||||
* @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved.
|
||||
* @default
|
||||
*/
|
||||
this.checkOffsetInterval = 2500;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
|
||||
*/
|
||||
this.currentRenderOrderID = 0;
|
||||
|
||||
/**
|
||||
* @property {string} hiddenVar - The page visibility API event name.
|
||||
* @private
|
||||
*/
|
||||
this._hiddenVar = 'hidden';
|
||||
|
||||
/**
|
||||
* @property {number} _nextOffsetCheck - The time to run the next offset check.
|
||||
* @private
|
||||
*/
|
||||
this._nextOffsetCheck = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _backgroundColor - Stage background color.
|
||||
* @private
|
||||
*/
|
||||
this._backgroundColor = 0x000000;
|
||||
|
||||
if (game.config)
|
||||
{
|
||||
this.parseConfig(game.config);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.game.canvas = Phaser.Canvas.create(width, height);
|
||||
this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Stage.prototype = Object.create(PIXI.Stage.prototype);
|
||||
Phaser.Stage.prototype.constructor = Phaser.Stage;
|
||||
|
||||
/**
|
||||
* This is called automatically after the plugins preUpdate and before the State.update.
|
||||
* Most objects have preUpdate methods and it's where initial movement and positioning is done.
|
||||
*
|
||||
* @method Phaser.Stage#preUpdate
|
||||
*/
|
||||
Phaser.Stage.prototype.preUpdate = function () {
|
||||
|
||||
this.currentRenderOrderID = 0;
|
||||
|
||||
// This can't loop in reverse, we need the orderID to be in sequence
|
||||
var len = this.children.length;
|
||||
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
this.children[i].preUpdate();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This is called automatically after the State.update, but before particles or plugins update.
|
||||
*
|
||||
* @method Phaser.Stage#update
|
||||
*/
|
||||
Phaser.Stage.prototype.update = function () {
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].update();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This is called automatically before the renderer runs and after the plugins have updated.
|
||||
* In postUpdate this is where all the final physics calculatations and object positioning happens.
|
||||
* The objects are processed in the order of the display list.
|
||||
* The only exception to this is if the camera is following an object, in which case that is updated first.
|
||||
*
|
||||
* @method Phaser.Stage#postUpdate
|
||||
*/
|
||||
Phaser.Stage.prototype.postUpdate = function () {
|
||||
|
||||
if (this.game.world.camera.target)
|
||||
{
|
||||
this.game.world.camera.target.postUpdate();
|
||||
|
||||
this.game.world.camera.update();
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
if (this.children[i] !== this.game.world.camera.target)
|
||||
{
|
||||
this.children[i].postUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.game.world.camera.update();
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].postUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
if (this.checkOffsetInterval !== false)
|
||||
{
|
||||
if (this.game.time.now > this._nextOffsetCheck)
|
||||
{
|
||||
Phaser.Canvas.getOffset(this.game.canvas, this.offset);
|
||||
this.bounds.x = this.offset.x;
|
||||
this.bounds.y = this.offset.y;
|
||||
this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Parses a Game configuration object.
|
||||
*
|
||||
* @method Phaser.Stage#parseConfig
|
||||
* @protected
|
||||
*/
|
||||
Phaser.Stage.prototype.parseConfig = function (config) {
|
||||
|
||||
if (config['canvasID'])
|
||||
{
|
||||
this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height, config['canvasID']);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.game.canvas = Phaser.Canvas.create(this.game.width, this.game.height);
|
||||
}
|
||||
|
||||
if (config['canvasStyle'])
|
||||
{
|
||||
this.game.canvas.stlye = config['canvasStyle'];
|
||||
}
|
||||
else
|
||||
{
|
||||
this.game.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
|
||||
}
|
||||
|
||||
if (config['checkOffsetInterval'])
|
||||
{
|
||||
this.checkOffsetInterval = config['checkOffsetInterval'];
|
||||
}
|
||||
|
||||
if (config['disableVisibilityChange'])
|
||||
{
|
||||
this.disableVisibilityChange = config['disableVisibilityChange'];
|
||||
}
|
||||
|
||||
if (config['fullScreenScaleMode'])
|
||||
{
|
||||
this.fullScreenScaleMode = config['fullScreenScaleMode'];
|
||||
}
|
||||
|
||||
if (config['scaleMode'])
|
||||
{
|
||||
this.scaleMode = config['scaleMode'];
|
||||
}
|
||||
|
||||
if (config['backgroundColor'])
|
||||
{
|
||||
this.backgroundColor = config['backgroundColor'];
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialises the stage and adds the event listeners.
|
||||
* @method Phaser.Stage#boot
|
||||
* @private
|
||||
*/
|
||||
Phaser.Stage.prototype.boot = function () {
|
||||
|
||||
Phaser.Canvas.getOffset(this.game.canvas, this.offset);
|
||||
|
||||
this.bounds.setTo(this.offset.x, this.offset.y, this.game.width, this.game.height);
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._onChange = function (event) {
|
||||
return _this.visibilityChange(event);
|
||||
};
|
||||
|
||||
Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
|
||||
Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
|
||||
|
||||
this.checkVisibility();
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Starts a page visibility event listener running, or window.blur/focus if not supported by the browser.
|
||||
* @method Phaser.Stage#checkVisibility
|
||||
*/
|
||||
Phaser.Stage.prototype.checkVisibility = function () {
|
||||
|
||||
if (document.webkitHidden !== undefined)
|
||||
{
|
||||
this._hiddenVar = 'webkitvisibilitychange';
|
||||
}
|
||||
else if (document.mozHidden !== undefined)
|
||||
{
|
||||
this._hiddenVar = 'mozvisibilitychange';
|
||||
}
|
||||
else if (document.msHidden !== undefined)
|
||||
{
|
||||
this._hiddenVar = 'msvisibilitychange';
|
||||
}
|
||||
else if (document.hidden !== undefined)
|
||||
{
|
||||
this._hiddenVar = 'visibilitychange';
|
||||
}
|
||||
else
|
||||
{
|
||||
this._hiddenVar = null;
|
||||
}
|
||||
|
||||
// Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
|
||||
if (this._hiddenVar)
|
||||
{
|
||||
document.addEventListener(this._hiddenVar, this._onChange, false);
|
||||
}
|
||||
|
||||
window.onpagehide = this._onChange;
|
||||
window.onpageshow = this._onChange;
|
||||
|
||||
window.onblur = this._onChange;
|
||||
window.onfocus = this._onChange;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This method is called when the document visibility is changed.
|
||||
* @method Phaser.Stage#visibilityChange
|
||||
* @param {Event} event - Its type will be used to decide whether the game should be paused or not.
|
||||
*/
|
||||
Phaser.Stage.prototype.visibilityChange = function (event) {
|
||||
|
||||
if (this.disableVisibilityChange)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
|
||||
{
|
||||
if (event.type === 'pagehide' || event.type === 'blur')
|
||||
{
|
||||
this.game.focusLoss(event);
|
||||
}
|
||||
else if (event.type === 'pageshow' || event.type === 'focus')
|
||||
{
|
||||
this.game.focusGain(event);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden)
|
||||
{
|
||||
this.game.gamePaused(event);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.game.gameResumed(event);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the background color for the Stage. The color can be given as a hex value (#RRGGBB) or a numeric value (0xRRGGBB)
|
||||
*
|
||||
* @name Phaser.Stage#setBackgroundColor
|
||||
* @param {number|string} backgroundColor - The color of the background.
|
||||
*/
|
||||
Phaser.Stage.prototype.setBackgroundColor = function(backgroundColor)
|
||||
{
|
||||
if (typeof backgroundColor === 'string')
|
||||
{
|
||||
var rgb = Phaser.Color.hexToColor(backgroundColor);
|
||||
this._backgroundColor = Phaser.Color.getColor(rgb.r, rgb.g, rgb.b);
|
||||
}
|
||||
else
|
||||
{
|
||||
var rgb = Phaser.Color.getRGB(backgroundColor);
|
||||
this._backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
this.backgroundColorSplit = [ rgb.r / 255, rgb.g / 255, rgb.b / 255 ];
|
||||
this.backgroundColorString = Phaser.Color.RGBtoString(rgb.r, rgb.g, rgb.b, 255, '#');
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Stage#backgroundColor
|
||||
* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000'
|
||||
*/
|
||||
Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this._backgroundColor;
|
||||
|
||||
},
|
||||
|
||||
set: function (color) {
|
||||
|
||||
if (!this.game.transparent)
|
||||
{
|
||||
this.setBackgroundColor(color);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
|
||||
*
|
||||
* @name Phaser.Stage#smoothed
|
||||
* @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
|
||||
*/
|
||||
Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !PIXI.scaleModes.LINEAR;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
PIXI.scaleModes.LINEAR = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
PIXI.scaleModes.LINEAR = 1;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
188
src/core/State.js
Normal file
188
src/core/State.js
Normal file
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a base State class which can be extended if you are creating your own game.
|
||||
* It provides quick access to common functions such as the camera, cache, input, match, sound and more.
|
||||
*
|
||||
* @class Phaser.State
|
||||
* @constructor
|
||||
*/
|
||||
|
||||
Phaser.State = function () {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - This is a reference to the currently running Game.
|
||||
*/
|
||||
this.game = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World.
|
||||
*/
|
||||
this.add = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects.
|
||||
*/
|
||||
this.make = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Camera} camera - A handy reference to World.camera.
|
||||
*/
|
||||
this.camera = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more.
|
||||
*/
|
||||
this.cache = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Input} input - A reference to the Input Manager.
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets.
|
||||
*/
|
||||
this.load = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Math} math - A reference to Math class with lots of helpful functions.
|
||||
*/
|
||||
this.math = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume.
|
||||
*/
|
||||
this.sound = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays.
|
||||
*/
|
||||
this.scale = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Stage} stage - A reference to the Stage.
|
||||
*/
|
||||
this.stage = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Time} time - A reference to the game clock and timed events system.
|
||||
*/
|
||||
this.time = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.TweenManager} tweens - A reference to the tween manager.
|
||||
*/
|
||||
this.tweens = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution.
|
||||
*/
|
||||
this.world = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created.
|
||||
*/
|
||||
this.particles = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser.
|
||||
*/
|
||||
this.physics = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator.
|
||||
*/
|
||||
this.rnd = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.State.prototype = {
|
||||
|
||||
/**
|
||||
* preload is called first. Normally you'd use this to load your game assets (or those needed for the current State)
|
||||
* You shouldn't create any objects in this method that require assets that you're also loading in this method, as
|
||||
* they won't yet be available.
|
||||
*
|
||||
* @method Phaser.State#preload
|
||||
*/
|
||||
preload: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
|
||||
*
|
||||
* @method Phaser.State#loadUpdate
|
||||
*/
|
||||
loadUpdate: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
|
||||
* The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist.
|
||||
*
|
||||
* @method Phaser.State#loadRender
|
||||
*/
|
||||
loadRender: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* create is called once preload has completed, this includes the loading of any assets from the Loader.
|
||||
* If you don't have a preload method then create is the first method called in your State.
|
||||
*
|
||||
* @method Phaser.State#create
|
||||
*/
|
||||
create: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* The update method is left empty for your own use.
|
||||
* It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called.
|
||||
* If is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called.
|
||||
*
|
||||
* @method Phaser.State#update
|
||||
*/
|
||||
update: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* Nearly all display objects in Phaser render automatically, you don't need to tell them to render.
|
||||
* However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any
|
||||
* final post-processing style effects here. Note that this happens before plugins postRender takes place.
|
||||
*
|
||||
* @method Phaser.State#render
|
||||
*/
|
||||
render: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* This method will be called if the core game loop is paused.
|
||||
*
|
||||
* @method Phaser.State#paused
|
||||
*/
|
||||
paused: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate.
|
||||
*
|
||||
* @method Phaser.State#pauseUpdate
|
||||
*/
|
||||
pauseUpdate: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* This method will be called when the State is shutdown (i.e. you switch to another state from this one).
|
||||
*
|
||||
* @method Phaser.State#shutdown
|
||||
*/
|
||||
shutdown: function () {
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.State.prototype.constructor = Phaser.State;
|
||||
637
src/core/StateManager.js
Normal file
637
src/core/StateManager.js
Normal file
@@ -0,0 +1,637 @@
|
||||
/* jshint newcap: false */
|
||||
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The State Manager is responsible for loading, setting up and switching game states.
|
||||
*
|
||||
* @class Phaser.StateManager
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
|
||||
*/
|
||||
Phaser.StateManager = function (game, pendingState) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Object} states - The object containing Phaser.States.
|
||||
*/
|
||||
this.states = {};
|
||||
|
||||
/**
|
||||
* @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
|
||||
* @private
|
||||
*/
|
||||
this._pendingState = null;
|
||||
|
||||
if (typeof pendingState !== 'undefined' && pendingState !== null)
|
||||
{
|
||||
this._pendingState = pendingState;
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {boolean} _clearWorld - Clear the world when we switch state?
|
||||
* @private
|
||||
*/
|
||||
this._clearWorld = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} _clearCache - Clear the cache when we switch state?
|
||||
* @private
|
||||
*/
|
||||
this._clearCache = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} _created - Flag that sets if the State has been created or not.
|
||||
* @private
|
||||
*/
|
||||
this._created = false;
|
||||
|
||||
/**
|
||||
* @property {array} _args - Temporary container when you pass vars from one State to another.
|
||||
* @private
|
||||
*/
|
||||
this._args = [];
|
||||
|
||||
/**
|
||||
* @property {string} current - The current active State object (defaults to null).
|
||||
*/
|
||||
this.current = '';
|
||||
|
||||
/**
|
||||
* @property {function} onInitCallback - This will be called when the state is started (i.e. set as the current active state).
|
||||
*/
|
||||
this.onInitCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onPreloadCallback - This will be called when init states (loading assets...).
|
||||
*/
|
||||
this.onPreloadCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onCreateCallback - This will be called when create states (setup states...).
|
||||
*/
|
||||
this.onCreateCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onUpdateCallback - This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback).
|
||||
*/
|
||||
this.onUpdateCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onRenderCallback - This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback).
|
||||
*/
|
||||
this.onRenderCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onPreRenderCallback - This will be called before the State is rendered and before the stage is cleared.
|
||||
*/
|
||||
this.onPreRenderCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onLoadUpdateCallback - This will be called when the State is updated but only during the load process.
|
||||
*/
|
||||
this.onLoadUpdateCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onLoadRenderCallback - This will be called when the State is rendered but only during the load process.
|
||||
*/
|
||||
this.onLoadRenderCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onPausedCallback - This will be called once each time the game is paused.
|
||||
*/
|
||||
this.onPausedCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onResumedCallback - This will be called once each time the game is resumed from a paused state.
|
||||
*/
|
||||
this.onResumedCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onPauseUpdateCallback - This will be called every frame while the game is paused.
|
||||
*/
|
||||
this.onPauseUpdateCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onShutDownCallback - This will be called when the state is shut down (i.e. swapped to another state).
|
||||
*/
|
||||
this.onShutDownCallback = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.StateManager.prototype = {
|
||||
|
||||
/**
|
||||
* The Boot handler is called by Phaser.Game when it first starts up.
|
||||
* @method Phaser.StateManager#boot
|
||||
* @private
|
||||
*/
|
||||
boot: function () {
|
||||
|
||||
this.game.onPause.add(this.pause, this);
|
||||
this.game.onResume.add(this.resume, this);
|
||||
this.game.load.onLoadComplete.add(this.loadComplete, this);
|
||||
|
||||
if (this._pendingState !== null)
|
||||
{
|
||||
if (typeof this._pendingState === 'string')
|
||||
{
|
||||
// State was already added, so just start it
|
||||
this.start(this._pendingState, false, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.add('default', this._pendingState, true);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
|
||||
* The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
|
||||
* If a function is given a new state object will be created by calling it.
|
||||
*
|
||||
* @method Phaser.StateManager#add
|
||||
* @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
|
||||
* @param {Phaser.State|object|function} state - The state you want to switch to.
|
||||
* @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
|
||||
*/
|
||||
add: function (key, state, autoStart) {
|
||||
|
||||
if (typeof autoStart === "undefined") { autoStart = false; }
|
||||
|
||||
var newState;
|
||||
|
||||
if (state instanceof Phaser.State)
|
||||
{
|
||||
newState = state;
|
||||
}
|
||||
else if (typeof state === 'object')
|
||||
{
|
||||
newState = state;
|
||||
newState.game = this.game;
|
||||
}
|
||||
else if (typeof state === 'function')
|
||||
{
|
||||
newState = new state(this.game);
|
||||
}
|
||||
|
||||
this.states[key] = newState;
|
||||
|
||||
if (autoStart)
|
||||
{
|
||||
if (this.game.isBooted)
|
||||
{
|
||||
this.start(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._pendingState = key;
|
||||
}
|
||||
}
|
||||
|
||||
return newState;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete the given state.
|
||||
* @method Phaser.StateManager#remove
|
||||
* @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
|
||||
*/
|
||||
remove: function (key) {
|
||||
|
||||
if (this.current === key)
|
||||
{
|
||||
this.callbackContext = null;
|
||||
|
||||
this.onInitCallback = null;
|
||||
this.onShutDownCallback = null;
|
||||
|
||||
this.onPreloadCallback = null;
|
||||
this.onLoadRenderCallback = null;
|
||||
this.onLoadUpdateCallback = null;
|
||||
this.onCreateCallback = null;
|
||||
this.onUpdateCallback = null;
|
||||
this.onRenderCallback = null;
|
||||
this.onPausedCallback = null;
|
||||
this.onResumedCallback = null;
|
||||
this.onPauseUpdateCallback = null;
|
||||
}
|
||||
|
||||
delete this.states[key];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State.
|
||||
*
|
||||
* @method Phaser.StateManager#start
|
||||
* @param {string} key - The key of the state you want to start.
|
||||
* @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
|
||||
* @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
|
||||
* @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
|
||||
*/
|
||||
start: function (key, clearWorld, clearCache) {
|
||||
|
||||
if (typeof clearWorld === "undefined") { clearWorld = true; }
|
||||
if (typeof clearCache === "undefined") { clearCache = false; }
|
||||
|
||||
if (this.checkState(key))
|
||||
{
|
||||
// Place the state in the queue. It will be started the next time the game loop starts.
|
||||
this._pendingState = key;
|
||||
this._clearWorld = clearWorld;
|
||||
this._clearCache = clearCache;
|
||||
|
||||
if (arguments.length > 3)
|
||||
{
|
||||
this._args = Array.prototype.splice.call(arguments, 3);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
|
||||
*
|
||||
* @method Phaser.StateManager#restart
|
||||
* @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
|
||||
* @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
|
||||
* @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
|
||||
*/
|
||||
restart: function (clearWorld, clearCache) {
|
||||
|
||||
if (typeof clearWorld === "undefined") { clearWorld = true; }
|
||||
if (typeof clearCache === "undefined") { clearCache = false; }
|
||||
|
||||
// Place the state in the queue. It will be started the next time the game loop starts.
|
||||
this._pendingState = this.current;
|
||||
this._clearWorld = clearWorld;
|
||||
this._clearCache = clearCache;
|
||||
|
||||
if (arguments.length > 2)
|
||||
{
|
||||
this._args = Array.prototype.splice.call(arguments, 2);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Used by onInit and onShutdown when those functions don't exist on the state
|
||||
* @method Phaser.StateManager#dummy
|
||||
* @private
|
||||
*/
|
||||
dummy: function () {
|
||||
},
|
||||
|
||||
/**
|
||||
* preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
|
||||
*
|
||||
* @method Phaser.StateManager#preUpdate
|
||||
*/
|
||||
preUpdate: function () {
|
||||
|
||||
if (this._pendingState && this.game.isBooted)
|
||||
{
|
||||
// Already got a state running?
|
||||
if (this.current)
|
||||
{
|
||||
this.onShutDownCallback.call(this.callbackContext, this.game);
|
||||
|
||||
this.game.tweens.removeAll();
|
||||
|
||||
this.game.camera.reset();
|
||||
|
||||
this.game.input.reset(true);
|
||||
|
||||
this.game.physics.clear();
|
||||
|
||||
this.game.time.removeAll();
|
||||
|
||||
if (this._clearWorld)
|
||||
{
|
||||
this.game.world.shutdown();
|
||||
|
||||
if (this._clearCache === true)
|
||||
{
|
||||
this.game.cache.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.setCurrentState(this._pendingState);
|
||||
|
||||
if (this.onPreloadCallback)
|
||||
{
|
||||
this.game.load.reset();
|
||||
this.onPreloadCallback.call(this.callbackContext, this.game);
|
||||
|
||||
// Is the loader empty?
|
||||
if (this.game.load.totalQueuedFiles() === 0)
|
||||
{
|
||||
this.loadComplete();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Start the loader going as we have something in the queue
|
||||
this.game.load.start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// No init? Then there was nothing to load either
|
||||
this.loadComplete();
|
||||
}
|
||||
|
||||
if (this.current === this._pendingState)
|
||||
{
|
||||
this._pendingState = null;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render.
|
||||
*
|
||||
* @method Phaser.StateManager#checkState
|
||||
* @param {string} key - The key of the state you want to check.
|
||||
* @return {boolean} true if the State has the required functions, otherwise false.
|
||||
*/
|
||||
checkState: function (key) {
|
||||
|
||||
if (this.states[key])
|
||||
{
|
||||
var valid = false;
|
||||
|
||||
if (this.states[key]['preload']) { valid = true; }
|
||||
if (this.states[key]['create']) { valid = true; }
|
||||
if (this.states[key]['update']) { valid = true; }
|
||||
if (this.states[key]['render']) { valid = true; }
|
||||
|
||||
if (valid === false)
|
||||
{
|
||||
console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
console.warn("Phaser.StateManager - No state found with the key: " + key);
|
||||
return false;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Links game properties to the State given by the key.
|
||||
*
|
||||
* @method Phaser.StateManager#link
|
||||
* @param {string} key - State key.
|
||||
* @protected
|
||||
*/
|
||||
link: function (key) {
|
||||
|
||||
this.states[key].game = this.game;
|
||||
this.states[key].add = this.game.add;
|
||||
this.states[key].make = this.game.make;
|
||||
this.states[key].camera = this.game.camera;
|
||||
this.states[key].cache = this.game.cache;
|
||||
this.states[key].input = this.game.input;
|
||||
this.states[key].load = this.game.load;
|
||||
this.states[key].math = this.game.math;
|
||||
this.states[key].sound = this.game.sound;
|
||||
this.states[key].scale = this.game.scale;
|
||||
this.states[key].state = this;
|
||||
this.states[key].stage = this.game.stage;
|
||||
this.states[key].time = this.game.time;
|
||||
this.states[key].tweens = this.game.tweens;
|
||||
this.states[key].world = this.game.world;
|
||||
this.states[key].particles = this.game.particles;
|
||||
this.states[key].rnd = this.game.rnd;
|
||||
this.states[key].physics = this.game.physics;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the current State. Should not be called directly (use StateManager.start)
|
||||
*
|
||||
* @method Phaser.StateManager#setCurrentState
|
||||
* @param {string} key - State key.
|
||||
* @private
|
||||
*/
|
||||
setCurrentState: function (key) {
|
||||
|
||||
this.callbackContext = this.states[key];
|
||||
|
||||
this.link(key);
|
||||
|
||||
// Used when the state is set as being the current active state
|
||||
this.onInitCallback = this.states[key]['init'] || this.dummy;
|
||||
|
||||
this.onPreloadCallback = this.states[key]['preload'] || null;
|
||||
this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
|
||||
this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
|
||||
this.onCreateCallback = this.states[key]['create'] || null;
|
||||
this.onUpdateCallback = this.states[key]['update'] || null;
|
||||
this.onPreRenderCallback = this.states[key]['preRender'] || null;
|
||||
this.onRenderCallback = this.states[key]['render'] || null;
|
||||
this.onPausedCallback = this.states[key]['paused'] || null;
|
||||
this.onResumedCallback = this.states[key]['resumed'] || null;
|
||||
this.onPauseUpdateCallback = this.states[key]['pauseUpdate'] || null;
|
||||
|
||||
// Used when the state is no longer the current active state
|
||||
this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
|
||||
|
||||
this.current = key;
|
||||
this._created = false;
|
||||
|
||||
this.onInitCallback.apply(this.callbackContext, this._args);
|
||||
|
||||
this._args = [];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets the current State.
|
||||
*
|
||||
* @method Phaser.StateManager#getCurrentState
|
||||
* @return Phaser.State
|
||||
* @public
|
||||
*/
|
||||
getCurrentState: function() {
|
||||
return this.states[this.current];
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#loadComplete
|
||||
* @protected
|
||||
*/
|
||||
loadComplete: function () {
|
||||
|
||||
if (this._created === false && this.onCreateCallback)
|
||||
{
|
||||
this._created = true;
|
||||
this.onCreateCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._created = true;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#pause
|
||||
* @protected
|
||||
*/
|
||||
pause: function () {
|
||||
|
||||
if (this._created && this.onPausedCallback)
|
||||
{
|
||||
this.onPausedCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#resume
|
||||
* @protected
|
||||
*/
|
||||
resume: function () {
|
||||
|
||||
if (this._created && this.onResumedCallback)
|
||||
{
|
||||
this.onResumedCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#update
|
||||
* @protected
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
if (this._created && this.onUpdateCallback)
|
||||
{
|
||||
this.onUpdateCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.onLoadUpdateCallback)
|
||||
{
|
||||
this.onLoadUpdateCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#pauseUpdate
|
||||
* @protected
|
||||
*/
|
||||
pauseUpdate: function () {
|
||||
|
||||
if (this._created && this.onPauseUpdateCallback)
|
||||
{
|
||||
this.onPauseUpdateCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.onLoadUpdateCallback)
|
||||
{
|
||||
this.onLoadUpdateCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#preRender
|
||||
* @protected
|
||||
*/
|
||||
preRender: function () {
|
||||
|
||||
if (this.onPreRenderCallback)
|
||||
{
|
||||
this.onPreRenderCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.StateManager#render
|
||||
* @protected
|
||||
*/
|
||||
render: function () {
|
||||
|
||||
if (this._created && this.onRenderCallback)
|
||||
{
|
||||
if (this.game.renderType === Phaser.CANVAS)
|
||||
{
|
||||
this.game.context.save();
|
||||
this.game.context.setTransform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
|
||||
this.onRenderCallback.call(this.callbackContext, this.game);
|
||||
|
||||
if (this.game.renderType === Phaser.CANVAS)
|
||||
{
|
||||
this.game.context.restore();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.onLoadRenderCallback)
|
||||
{
|
||||
this.onLoadRenderCallback.call(this.callbackContext, this.game);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
|
||||
* You don't recover from this without rebuilding the Phaser instance again.
|
||||
* @method Phaser.StateManager#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.callbackContext = null;
|
||||
|
||||
this.onInitCallback = null;
|
||||
this.onShutDownCallback = null;
|
||||
|
||||
this.onPreloadCallback = null;
|
||||
this.onLoadRenderCallback = null;
|
||||
this.onLoadUpdateCallback = null;
|
||||
this.onCreateCallback = null;
|
||||
this.onUpdateCallback = null;
|
||||
this.onRenderCallback = null;
|
||||
this.onPausedCallback = null;
|
||||
this.onResumedCallback = null;
|
||||
this.onPauseUpdateCallback = null;
|
||||
|
||||
this.game = null;
|
||||
this.states = {};
|
||||
this._pendingState = null;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.StateManager.prototype.constructor = Phaser.StateManager;
|
||||
266
src/core/World.js
Normal file
266
src/core/World.js
Normal file
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* "This world is but a canvas to our imagination." - Henry David Thoreau
|
||||
*
|
||||
* A game has only one world. The world is an abstract place in which all game objects live. It is not bound
|
||||
* by stage limits and can be any size. You look into the world via cameras. All game objects live within
|
||||
* the world at world-based coordinates. By default a world is created the same size as your Stage.
|
||||
*
|
||||
* @class Phaser.World
|
||||
* @extends Phaser.Group
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Reference to the current game instance.
|
||||
*/
|
||||
Phaser.World = function (game) {
|
||||
|
||||
Phaser.Group.call(this, game, null, '__world', false);
|
||||
|
||||
/**
|
||||
* The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects.
|
||||
* By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display.
|
||||
* However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0.
|
||||
* So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0.
|
||||
* @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
|
||||
*/
|
||||
this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Camera} camera - Camera instance.
|
||||
*/
|
||||
this.camera = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.World.prototype = Object.create(Phaser.Group.prototype);
|
||||
Phaser.World.prototype.constructor = Phaser.World;
|
||||
|
||||
/**
|
||||
* Initialises the game world.
|
||||
*
|
||||
* @method Phaser.World#boot
|
||||
* @protected
|
||||
*/
|
||||
Phaser.World.prototype.boot = function () {
|
||||
|
||||
this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
|
||||
|
||||
this.camera.displayObject = this;
|
||||
|
||||
this.camera.scale = this.scale;
|
||||
|
||||
this.game.camera = this.camera;
|
||||
|
||||
this.game.stage.addChild(this);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
|
||||
*
|
||||
* @method Phaser.World#setBounds
|
||||
* @param {number} x - Top left most corner of the world.
|
||||
* @param {number} y - Top left most corner of the world.
|
||||
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
|
||||
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
|
||||
*/
|
||||
Phaser.World.prototype.setBounds = function (x, y, width, height) {
|
||||
|
||||
if (width < this.game.width)
|
||||
{
|
||||
width = this.game.width;
|
||||
}
|
||||
|
||||
if (height < this.game.height)
|
||||
{
|
||||
height = this.game.height;
|
||||
}
|
||||
|
||||
this.bounds.setTo(x, y, width, height);
|
||||
|
||||
if (this.camera.bounds)
|
||||
{
|
||||
// The Camera can never be smaller than the game size
|
||||
this.camera.bounds.setTo(x, y, width, height);
|
||||
}
|
||||
|
||||
this.game.physics.setBoundsToWorld();
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroyer of worlds.
|
||||
*
|
||||
* @method Phaser.World#shutdown
|
||||
*/
|
||||
Phaser.World.prototype.shutdown = function () {
|
||||
|
||||
// World is a Group, so run a soft destruction on this and all children.
|
||||
this.destroy(true, true);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This will take the given game object and check if its x/y coordinates fall outside of the world bounds.
|
||||
* If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect.
|
||||
*
|
||||
* @method Phaser.World#wrap
|
||||
* @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds.
|
||||
* @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true.
|
||||
* @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive.
|
||||
*/
|
||||
Phaser.World.prototype.wrap = function (sprite, padding, useBounds) {
|
||||
|
||||
if (typeof padding === 'undefined') { padding = 0; }
|
||||
if (typeof useBounds === 'undefined') { useBounds = false; }
|
||||
|
||||
if (!useBounds)
|
||||
{
|
||||
if (sprite.x + padding < this.bounds.x)
|
||||
{
|
||||
sprite.x = this.bounds.right + padding;
|
||||
}
|
||||
else if (sprite.x - padding > this.bounds.right)
|
||||
{
|
||||
sprite.x = this.bounds.left - padding;
|
||||
}
|
||||
|
||||
if (sprite.y + padding < this.bounds.top)
|
||||
{
|
||||
sprite.y = this.bounds.bottom + padding;
|
||||
}
|
||||
else if (sprite.y - padding > this.bounds.bottom)
|
||||
{
|
||||
sprite.y = this.bounds.top - padding;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
sprite.getBounds();
|
||||
|
||||
if (sprite._currentBounds.right < this.bounds.x)
|
||||
{
|
||||
sprite.x = this.bounds.right;
|
||||
}
|
||||
else if (sprite._currentBounds.x > this.bounds.right)
|
||||
{
|
||||
sprite.x = this.bounds.left;
|
||||
}
|
||||
|
||||
if (sprite._currentBounds.bottom < this.bounds.top)
|
||||
{
|
||||
sprite.y = this.bounds.bottom;
|
||||
}
|
||||
else if (sprite._currentBounds.top > this.bounds.bottom)
|
||||
{
|
||||
sprite.y = this.bounds.top;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.World#width
|
||||
* @property {number} width - Gets or sets the current width of the game world.
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "width", {
|
||||
|
||||
get: function () {
|
||||
return this.bounds.width;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.bounds.width = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.World#height
|
||||
* @property {number} height - Gets or sets the current height of the game world.
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "height", {
|
||||
|
||||
get: function () {
|
||||
return this.bounds.height;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.bounds.height = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.World#centerX
|
||||
* @property {number} centerX - Gets the X position corresponding to the center point of the world.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "centerX", {
|
||||
|
||||
get: function () {
|
||||
return this.bounds.halfWidth;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.World#centerY
|
||||
* @property {number} centerY - Gets the Y position corresponding to the center point of the world.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "centerY", {
|
||||
|
||||
get: function () {
|
||||
return this.bounds.halfHeight;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.World#randomX
|
||||
* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "randomX", {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.bounds.x < 0)
|
||||
{
|
||||
return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.World#randomY
|
||||
* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.World.prototype, "randomY", {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.bounds.y < 0)
|
||||
{
|
||||
return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
925
src/gameobjects/BitmapData.js
Normal file
925
src/gameobjects/BitmapData.js
Normal file
@@ -0,0 +1,925 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new BitmapData object.
|
||||
*
|
||||
* @class Phaser.BitmapData
|
||||
*
|
||||
* @classdesc A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
|
||||
* A single BitmapData can be used as the texture one or many Images/Sprites. So if you need to dynamically create a Sprite texture then they are a good choice.
|
||||
*
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {string} key - Internal Phaser reference key for the render texture.
|
||||
* @param {number} [width=100] - The width of the BitmapData in pixels.
|
||||
* @param {number} [height=100] - The height of the BitmapData in pixels.
|
||||
*/
|
||||
Phaser.BitmapData = function (game, key, width, height) {
|
||||
|
||||
if (typeof width === 'undefined') { width = 100; }
|
||||
if (typeof height === 'undefined') { height = 100; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {string} key - The key of the BitmapData in the Cache, if stored there.
|
||||
*/
|
||||
this.key = key;
|
||||
|
||||
/**
|
||||
* @property {number} width - The width of the BitmapData in pixels.
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - The height of the BitmapData in pixels.
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
|
||||
* @default
|
||||
*/
|
||||
this.canvas = Phaser.Canvas.create(width, height, '', true);
|
||||
|
||||
/**
|
||||
* @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
|
||||
* @default
|
||||
*/
|
||||
this.context = this.canvas.getContext('2d');
|
||||
|
||||
/**
|
||||
* @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
|
||||
*/
|
||||
this.ctx = this.context;
|
||||
|
||||
/**
|
||||
* @property {ImageData} imageData - The context image data.
|
||||
*/
|
||||
this.imageData = this.context.getImageData(0, 0, width, height);
|
||||
|
||||
/**
|
||||
* @property {Uint8ClampedArray} data - A Uint8ClampedArray view into BitmapData.buffer.
|
||||
*/
|
||||
this.data = this.imageData.data;
|
||||
|
||||
/**
|
||||
* @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer.
|
||||
*/
|
||||
this.pixels = null;
|
||||
|
||||
/**
|
||||
* @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData.
|
||||
*/
|
||||
if (this.imageData.data.buffer)
|
||||
{
|
||||
this.buffer = this.imageData.data.buffer;
|
||||
this.pixels = new Uint32Array(this.buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (window['ArrayBuffer'])
|
||||
{
|
||||
this.buffer = new ArrayBuffer(this.imageData.data.length);
|
||||
this.pixels = new Uint32Array(this.buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.pixels = this.imageData.data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
|
||||
* @default
|
||||
*/
|
||||
this.baseTexture = new PIXI.BaseTexture(this.canvas);
|
||||
|
||||
/**
|
||||
* @property {PIXI.Texture} texture - The PIXI.Texture.
|
||||
* @default
|
||||
*/
|
||||
this.texture = new PIXI.Texture(this.baseTexture);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
|
||||
* @default
|
||||
*/
|
||||
this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData', game.rnd.uuid());
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @default
|
||||
*/
|
||||
this.type = Phaser.BITMAPDATA;
|
||||
|
||||
/**
|
||||
* @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true.
|
||||
*/
|
||||
this.disableTextureUpload = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} dirty - If dirty this BitmapData will be re-rendered.
|
||||
*/
|
||||
this.dirty = false;
|
||||
|
||||
// Aliases
|
||||
this.cls = this.clear;
|
||||
this.update = this.refreshBuffer;
|
||||
|
||||
/**
|
||||
* @property {number} _tempR - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._tempR = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _tempG - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._tempG = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _tempB - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._tempB = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.BitmapData.prototype = {
|
||||
|
||||
/**
|
||||
* Updates the given objects so that they use this BitmapData as their texture. This will replace any texture they will currently have set.
|
||||
*
|
||||
* @method Phaser.BitmapData#add
|
||||
* @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
|
||||
*/
|
||||
add: function (object) {
|
||||
|
||||
if (Array.isArray(object))
|
||||
{
|
||||
for (var i = 0; i < object.length; i++)
|
||||
{
|
||||
if (object[i]['loadTexture'])
|
||||
{
|
||||
object[i].loadTexture(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
object.loadTexture(this);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clears the BitmapData context using a clearRect.
|
||||
*
|
||||
* @method Phaser.BitmapData#cls
|
||||
*/
|
||||
|
||||
/**
|
||||
* Clears the BitmapData context using a clearRect.
|
||||
*
|
||||
* @method Phaser.BitmapData#clear
|
||||
*/
|
||||
clear: function () {
|
||||
|
||||
this.context.clearRect(0, 0, this.width, this.height);
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Fills the BitmapData with the given color.
|
||||
*
|
||||
* @method Phaser.BitmapData#fill
|
||||
* @param {number} r - The red color value, between 0 and 0xFF (255).
|
||||
* @param {number} g - The green color value, between 0 and 0xFF (255).
|
||||
* @param {number} b - The blue color value, between 0 and 0xFF (255).
|
||||
* @param {number} [a=1] - The alpha color value, between 0 and 1.
|
||||
*/
|
||||
fill: function (r, g, b, a) {
|
||||
|
||||
if (typeof a === 'undefined') { a = 1; }
|
||||
|
||||
this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
|
||||
this.context.fillRect(0, 0, this.width, this.height);
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer.
|
||||
*
|
||||
* @method Phaser.BitmapData#resize
|
||||
*/
|
||||
resize: function (width, height) {
|
||||
|
||||
if (width !== this.width || height !== this.height)
|
||||
{
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.canvas.width = width;
|
||||
this.canvas.height = height;
|
||||
this.textureFrame.width = width;
|
||||
this.textureFrame.height = height;
|
||||
this.refreshBuffer();
|
||||
}
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This re-creates the BitmapData.imageData from the current context.
|
||||
* It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
|
||||
* If not given the dimensions defaults to the full size of the context.
|
||||
*
|
||||
* @method Phaser.BitmapData#update
|
||||
* @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
|
||||
* @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
|
||||
* @param {number} [width] - The width of the image data area.
|
||||
* @param {number} [height] - The height of the image data area.
|
||||
*/
|
||||
|
||||
/**
|
||||
* DEPRECATED: This method will be removed in Phaser 2.1. Please use BitmapData.update instead.
|
||||
*
|
||||
* This re-creates the BitmapData.imageData from the current context.
|
||||
* It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
|
||||
* If not given the dimensions defaults to the full size of the context.
|
||||
*
|
||||
* @method Phaser.BitmapData#refreshBuffer
|
||||
* @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
|
||||
* @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
|
||||
* @param {number} [width] - The width of the image data area.
|
||||
* @param {number} [height] - The height of the image data area.
|
||||
*/
|
||||
refreshBuffer: function (x, y, width, height) {
|
||||
|
||||
if (typeof x === 'undefined') { x = 0; }
|
||||
if (typeof y === 'undefined') { y = 0; }
|
||||
if (typeof width === 'undefined') { width = this.width; }
|
||||
if (typeof height === 'undefined') { height = this.height; }
|
||||
|
||||
this.imageData = this.context.getImageData(x, y, width, height);
|
||||
this.data = this.imageData.data;
|
||||
|
||||
if (this.imageData.data.buffer)
|
||||
{
|
||||
this.buffer = this.imageData.data.buffer;
|
||||
this.pixels = new Uint32Array(this.buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (window['ArrayBuffer'])
|
||||
{
|
||||
this.buffer = new ArrayBuffer(this.imageData.data.length);
|
||||
this.pixels = new Uint32Array(this.buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.pixels = this.imageData.data;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback.
|
||||
* The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`.
|
||||
* Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha.
|
||||
* The `color` property is an Int32 of the full color. Note the endianess of this will change per system.
|
||||
* The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others.
|
||||
* The callback will also be sent the pixels x and y coordinates respectively.
|
||||
* The callback must return either `false`, in which case no change will be made to the pixel, or a new color object.
|
||||
* If a new color object is returned the pixel will be set to the r, g, b and a color values given within it.
|
||||
*
|
||||
* @method Phaser.BitmapData#processPixelRGB
|
||||
* @param {function} callback - The callback that will be sent each pixel color object to be processed.
|
||||
* @param {object} callbackContext - The context under which the callback will be called.
|
||||
* @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
|
||||
* @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
|
||||
* @param {number} [width] - The width of the region to process.
|
||||
* @param {number} [height] - The height of the region to process.
|
||||
*/
|
||||
processPixelRGB: function (callback, callbackContext, x, y, width, height) {
|
||||
|
||||
if (typeof x === 'undefined') { x = 0; }
|
||||
if (typeof y === 'undefined') { y = 0; }
|
||||
if (typeof width === 'undefined') { width = this.width; }
|
||||
if (typeof height === 'undefined') { height = this.height; }
|
||||
|
||||
var w = x + width;
|
||||
var h = y + height;
|
||||
var pixel = Phaser.Color.createColor();
|
||||
var result = { r: 0, g: 0, b: 0, a: 0 };
|
||||
var dirty = false;
|
||||
|
||||
for (var ty = y; ty < h; ty++)
|
||||
{
|
||||
for (var tx = x; tx < w; tx++)
|
||||
{
|
||||
Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel);
|
||||
|
||||
result = callback.call(callbackContext, pixel, tx, ty);
|
||||
|
||||
if (result !== false && result !== null && result !== undefined)
|
||||
{
|
||||
this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false);
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (dirty)
|
||||
{
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates.
|
||||
* Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped.
|
||||
* Note that the format of the color received will be different depending on if the system is big or little endian.
|
||||
* It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead.
|
||||
* The callback will also be sent the pixels x and y coordinates respectively.
|
||||
*
|
||||
* @method Phaser.BitmapData#processPixel
|
||||
* @param {function} callback - The callback that will be sent each pixel color to be processed.
|
||||
* @param {object} callbackContext - The context under which the callback will be called.
|
||||
* @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
|
||||
* @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
|
||||
* @param {number} [width] - The width of the region to process.
|
||||
* @param {number} [height] - The height of the region to process.
|
||||
*/
|
||||
processPixel: function (callback, callbackContext, x, y, width, height) {
|
||||
|
||||
if (typeof x === 'undefined') { x = 0; }
|
||||
if (typeof y === 'undefined') { y = 0; }
|
||||
if (typeof width === 'undefined') { width = this.width; }
|
||||
if (typeof height === 'undefined') { height = this.height; }
|
||||
|
||||
var w = x + width;
|
||||
var h = y + height;
|
||||
var pixel = 0;
|
||||
var result = 0;
|
||||
var dirty = false;
|
||||
|
||||
for (var ty = y; ty < h; ty++)
|
||||
{
|
||||
for (var tx = x; tx < w; tx++)
|
||||
{
|
||||
pixel = this.getPixel32(tx, ty);
|
||||
result = callback.call(callbackContext, pixel, tx, ty);
|
||||
|
||||
if (result !== pixel)
|
||||
{
|
||||
this.pixels[ty * this.width + tx] = result;
|
||||
dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (dirty)
|
||||
{
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values.
|
||||
* An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing.
|
||||
*
|
||||
* @method Phaser.BitmapData#replaceRGB
|
||||
* @param {number} r1 - The red color value to be replaced. Between 0 and 255.
|
||||
* @param {number} g1 - The green color value to be replaced. Between 0 and 255.
|
||||
* @param {number} b1 - The blue color value to be replaced. Between 0 and 255.
|
||||
* @param {number} a1 - The alpha color value to be replaced. Between 0 and 255.
|
||||
* @param {number} r2 - The red color value that is the replacement color. Between 0 and 255.
|
||||
* @param {number} g2 - The green color value that is the replacement color. Between 0 and 255.
|
||||
* @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255.
|
||||
* @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255.
|
||||
* @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData.
|
||||
*/
|
||||
replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) {
|
||||
|
||||
var sx = 0;
|
||||
var sy = 0;
|
||||
var w = this.width;
|
||||
var h = this.height;
|
||||
var source = Phaser.Color.packPixel(r1, g1, b1, a1);
|
||||
|
||||
if (region !== undefined && region instanceof Phaser.Rectangle)
|
||||
{
|
||||
sx = region.x;
|
||||
sy = region.y;
|
||||
w = region.width;
|
||||
h = region.height;
|
||||
}
|
||||
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
if (this.getPixel32(sx + x, sy + y) === source)
|
||||
{
|
||||
this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
|
||||
*
|
||||
* @method Phaser.BitmapData#setHSL
|
||||
* @param {number} [h=null] - The hue, in the range 0 - 1.
|
||||
* @param {number} [s=null] - The saturation, in the range 0 - 1.
|
||||
* @param {number} [l=null] - The lightness, in the range 0 - 1.
|
||||
* @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
|
||||
*/
|
||||
setHSL: function (h, s, l, region) {
|
||||
|
||||
if (typeof h === 'undefined' || h === null) { h = false; }
|
||||
if (typeof s === 'undefined' || s === null) { s = false; }
|
||||
if (typeof l === 'undefined' || l === null) { l = false; }
|
||||
|
||||
if (!h && !s && !l)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof region === 'undefined')
|
||||
{
|
||||
region = new Phaser.Rectangle(0, 0, this.width, this.height);
|
||||
}
|
||||
|
||||
var pixel = Phaser.Color.createColor();
|
||||
|
||||
for (var y = region.y; y < region.bottom; y++)
|
||||
{
|
||||
for (var x = region.x; x < region.right; x++)
|
||||
{
|
||||
Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
|
||||
|
||||
if (h)
|
||||
{
|
||||
pixel.h = h;
|
||||
}
|
||||
|
||||
if (s)
|
||||
{
|
||||
pixel.s = s;
|
||||
}
|
||||
|
||||
if (l)
|
||||
{
|
||||
pixel.l = l;
|
||||
}
|
||||
|
||||
Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
|
||||
this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
|
||||
* Shifting will add the given value onto the current h, s and l values, not replace them.
|
||||
* The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1.
|
||||
*
|
||||
* @method Phaser.BitmapData#shiftHSL
|
||||
* @param {number} [h=null] - The amount to shift the hue by.
|
||||
* @param {number} [s=null] - The amount to shift the saturation by.
|
||||
* @param {number} [l=null] - The amount to shift the lightness by.
|
||||
* @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
|
||||
*/
|
||||
shiftHSL: function (h, s, l, region) {
|
||||
|
||||
if (typeof h === 'undefined' || h === null) { h = false; }
|
||||
if (typeof s === 'undefined' || s === null) { s = false; }
|
||||
if (typeof l === 'undefined' || l === null) { l = false; }
|
||||
|
||||
if (!h && !s && !l)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof region === 'undefined')
|
||||
{
|
||||
region = new Phaser.Rectangle(0, 0, this.width, this.height);
|
||||
}
|
||||
|
||||
var pixel = Phaser.Color.createColor();
|
||||
|
||||
for (var y = region.y; y < region.bottom; y++)
|
||||
{
|
||||
for (var x = region.x; x < region.right; x++)
|
||||
{
|
||||
Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
|
||||
|
||||
if (h)
|
||||
{
|
||||
pixel.h = this.game.math.wrap(pixel.h + h, 0, 1);
|
||||
}
|
||||
|
||||
if (s)
|
||||
{
|
||||
pixel.s = this.game.math.limitValue(pixel.s + s, 0, 1);
|
||||
}
|
||||
|
||||
if (l)
|
||||
{
|
||||
pixel.l = this.game.math.limitValue(pixel.l + l, 0, 1);
|
||||
}
|
||||
|
||||
Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
|
||||
this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
|
||||
}
|
||||
}
|
||||
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the color of the given pixel to the specified red, green, blue and alpha values.
|
||||
*
|
||||
* @method Phaser.BitmapData#setPixel32
|
||||
* @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} red - The red color value, between 0 and 0xFF (255).
|
||||
* @param {number} green - The green color value, between 0 and 0xFF (255).
|
||||
* @param {number} blue - The blue color value, between 0 and 0xFF (255).
|
||||
* @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
|
||||
* @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
|
||||
*/
|
||||
setPixel32: function (x, y, red, green, blue, alpha, immediate) {
|
||||
|
||||
if (typeof immediate === 'undefined') { immediate = true; }
|
||||
|
||||
if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
|
||||
{
|
||||
if (Phaser.Device.LITTLE_ENDIAN)
|
||||
{
|
||||
this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.pixels[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
|
||||
}
|
||||
|
||||
if (immediate)
|
||||
{
|
||||
this.context.putImageData(this.imageData, 0, 0);
|
||||
this.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the color of the given pixel to the specified red, green and blue values.
|
||||
*
|
||||
* @method Phaser.BitmapData#setPixel
|
||||
* @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} red - The red color value, between 0 and 0xFF (255).
|
||||
* @param {number} green - The green color value, between 0 and 0xFF (255).
|
||||
* @param {number} blue - The blue color value, between 0 and 0xFF (255).
|
||||
* @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
|
||||
* @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
|
||||
*/
|
||||
setPixel: function (x, y, red, green, blue, immediate) {
|
||||
|
||||
this.setPixel32(x, y, red, green, blue, 255, immediate);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the color of a specific pixel in the context into a color object.
|
||||
* If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
|
||||
* otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
|
||||
*
|
||||
* @method Phaser.BitmapData#getPixel
|
||||
* @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
|
||||
* @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
|
||||
*/
|
||||
getPixel: function (x, y, out) {
|
||||
|
||||
if (!out)
|
||||
{
|
||||
out = Phaser.Color.createColor();
|
||||
}
|
||||
|
||||
var index = ~~(x + (y * this.width));
|
||||
|
||||
index *= 4;
|
||||
|
||||
if (this.data[index])
|
||||
{
|
||||
out.r = this.data[index];
|
||||
out.g = this.data[++index];
|
||||
out.b = this.data[++index];
|
||||
out.a = this.data[++index];
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the color of a specific pixel including its alpha value.
|
||||
* If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
|
||||
* otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
|
||||
* Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA.
|
||||
*
|
||||
* @method Phaser.BitmapData#getPixel32
|
||||
* @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @return {number} A native color value integer (format: 0xAARRGGBB)
|
||||
*/
|
||||
getPixel32: function (x, y) {
|
||||
|
||||
if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
|
||||
{
|
||||
return this.pixels[y * this.width + x];
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties.
|
||||
* If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
|
||||
* otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
|
||||
*
|
||||
* @method Phaser.BitmapData#getPixelRGB
|
||||
* @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
|
||||
* @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
|
||||
* @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
|
||||
* @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
|
||||
* @return {object} An object with the red, green and blue values set in the r, g and b properties.
|
||||
*/
|
||||
getPixelRGB: function (x, y, out, hsl, hsv) {
|
||||
|
||||
return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets all the pixels from the region specified by the given Rectangle object.
|
||||
*
|
||||
* @method Phaser.BitmapData#getPixels
|
||||
* @param {Phaser.Rectangle} rect - The Rectangle region to get.
|
||||
* @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property.
|
||||
*/
|
||||
getPixels: function (rect) {
|
||||
|
||||
return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the pixels from the source image to this BitmapData based on the given area and destination.
|
||||
*
|
||||
* @method Phaser.BitmapData#copyPixels
|
||||
* @param {HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
|
||||
* @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
|
||||
* @param {number} destX - The destination x coordinate to copy the image to.
|
||||
* @param {number} destY - The destination y coordinate to copy the image to.
|
||||
*/
|
||||
copyPixels: function (source, area, destX, destY) {
|
||||
|
||||
if (typeof source === 'string')
|
||||
{
|
||||
source = this.game.cache.getImage(source);
|
||||
}
|
||||
|
||||
if (source)
|
||||
{
|
||||
this.context.drawImage(source, area.x, area.y, area.width, area.height, destX, destY, area.width, area.height);
|
||||
}
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws the given image to this BitmapData at the coordinates specified. If you need to only draw a part of the image use BitmapData.copyPixels instead.
|
||||
*
|
||||
* @method Phaser.BitmapData#draw
|
||||
* @param {HTMLImage|string} source - The Image to draw. If you give a string it will try and find the Image in the Game.Cache.
|
||||
* @param {number} [x=0] - The x coordinate to draw the image to.
|
||||
* @param {number} [y=0] - The y coordinate to draw the image to.
|
||||
*/
|
||||
draw: function (source, x, y) {
|
||||
|
||||
if (typeof x === 'undefined') { x = 0; }
|
||||
if (typeof y === 'undefined') { y = 0; }
|
||||
|
||||
if (typeof source === 'string')
|
||||
{
|
||||
source = this.game.cache.getImage(source);
|
||||
}
|
||||
|
||||
if (source)
|
||||
{
|
||||
this.context.drawImage(source, 0, 0, source.width, source.height, x, y, source.width, source.height);
|
||||
}
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws the given image to this BitmapData at the coordinates specified. If you need to only draw a part of the image use BitmapData.copyPixels instead.
|
||||
*
|
||||
* @method Phaser.BitmapData#drawSprite
|
||||
* @param {Phaser.Sprite|Phaser.Image} sprite - The Sprite to draw. Must have a loaded texture and frame.
|
||||
* @param {number} [x=0] - The x coordinate to draw the Sprite to.
|
||||
* @param {number} [y=0] - The y coordinate to draw the Sprite to.
|
||||
*/
|
||||
drawSprite: function (sprite, x, y) {
|
||||
|
||||
if (typeof x === 'undefined') { x = 0; }
|
||||
if (typeof y === 'undefined') { y = 0; }
|
||||
|
||||
var frame = sprite.texture.frame;
|
||||
|
||||
this.context.drawImage(sprite.texture.baseTexture.source, frame.x, frame.y, frame.width, frame.height, x, y, frame.width, frame.height);
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws the given image onto this BitmapData using an image as an alpha mask.
|
||||
*
|
||||
* @method Phaser.BitmapData#alphaMask
|
||||
* @param {HTMLImage|string} source - The Image to draw. If you give a key it will try and find the Image in the Game.Cache.
|
||||
* @param {HTMLImage|string} mask - The Image to use as the alpha mask. If you give a key it will try and find the Image in the Game.Cache.
|
||||
*/
|
||||
alphaMask: function (source, mask) {
|
||||
|
||||
var temp = this.context.globalCompositeOperation;
|
||||
|
||||
if (typeof mask === 'string')
|
||||
{
|
||||
mask = this.game.cache.getImage(mask);
|
||||
}
|
||||
|
||||
if (mask)
|
||||
{
|
||||
this.context.drawImage(mask, 0, 0);
|
||||
}
|
||||
|
||||
this.context.globalCompositeOperation = 'source-atop';
|
||||
|
||||
if (typeof source === 'string')
|
||||
{
|
||||
source = this.game.cache.getImage(source);
|
||||
}
|
||||
|
||||
if (source)
|
||||
{
|
||||
this.context.drawImage(source, 0, 0);
|
||||
}
|
||||
|
||||
this.context.globalCompositeOperation = temp;
|
||||
|
||||
this.dirty = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData.
|
||||
* The destination BitmapData must be large enough to receive all of the pixels that are scanned.
|
||||
* Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid:
|
||||
* `picture.extract(mask, r, g, b)`
|
||||
*
|
||||
* @method Phaser.BitmapData#extract
|
||||
* @param {Phaser.BitmapData} destination - The BitmapData that the extracts pixels will be drawn to.
|
||||
* @param {number} r - The red color component, in the range 0 - 255.
|
||||
* @param {number} g - The green color component, in the range 0 - 255.
|
||||
* @param {number} b - The blue color component, in the range 0 - 255.
|
||||
* @param {number} [a=255] - The alpha color component, in the range 0 - 255.
|
||||
* @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on.
|
||||
*/
|
||||
extract: function (destination, r, g, b, a) {
|
||||
|
||||
if (typeof a === 'undefined') { a = 255; }
|
||||
|
||||
this.processPixelRGB(
|
||||
function(pixel, x, y){
|
||||
if (pixel.r === r && pixel.g === g && pixel.b === b)
|
||||
{
|
||||
destination.setPixel32(x, y, r, g, b, a, false);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
this);
|
||||
|
||||
destination.context.putImageData(destination.imageData, 0, 0);
|
||||
destination.dirty = true;
|
||||
|
||||
return destination;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size.
|
||||
*
|
||||
* @method Phaser.BitmapData#rect
|
||||
* @param {number} x - The x coordinate of the top-left of the Rectangle.
|
||||
* @param {number} y - The y coordinate of the top-left of the Rectangle.
|
||||
* @param {number} width - The width of the Rectangle.
|
||||
* @param {number} height - The height of the Rectangle.
|
||||
* @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn.
|
||||
*/
|
||||
rect: function (x, y, width, height, fillStyle) {
|
||||
|
||||
if (typeof fillStyle !== 'undefined')
|
||||
{
|
||||
this.context.fillStyle = fillStyle;
|
||||
}
|
||||
|
||||
this.context.fillRect(x, y, width, height);
|
||||
this.context.fill();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size.
|
||||
*
|
||||
* @method Phaser.BitmapData#circle
|
||||
* @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle.
|
||||
* @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle.
|
||||
* @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter.
|
||||
* @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn.
|
||||
*/
|
||||
circle: function (x, y, radius, fillStyle) {
|
||||
|
||||
if (typeof fillStyle !== 'undefined')
|
||||
{
|
||||
this.context.fillStyle = fillStyle;
|
||||
}
|
||||
|
||||
this.context.beginPath();
|
||||
this.context.arc(x, y, radius, 0, Math.PI * 2, false);
|
||||
this.context.closePath();
|
||||
|
||||
this.context.fill();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
|
||||
* This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function.
|
||||
* If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`.
|
||||
*
|
||||
* @method Phaser.BitmapData#render
|
||||
*/
|
||||
render: function () {
|
||||
|
||||
if (!this.disableTextureUpload && this.game.renderType === Phaser.WEBGL && this.dirty)
|
||||
{
|
||||
// Only needed if running in WebGL, otherwise this array will never get cleared down
|
||||
// should use the rendersession
|
||||
PIXI.updateWebGLTexture(this.baseTexture, this.game.renderer.gl);
|
||||
|
||||
this.dirty = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
|
||||
485
src/gameobjects/BitmapText.js
Normal file
485
src/gameobjects/BitmapText.js
Normal file
@@ -0,0 +1,485 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new BitmapText object.
|
||||
*
|
||||
* @class Phaser.BitmapText
|
||||
*
|
||||
* @classdesc BitmapText objects work by taking a texture file and an XML file that describes the font layout.
|
||||
*
|
||||
* On Windows you can use the free app BMFont: http://www.angelcode.com/products/bmfont/
|
||||
* On OS X we recommend Glyph Designer: http://www.71squared.com/en/glyphdesigner
|
||||
* For Web there is the great Littera: http://kvazars.com/littera/
|
||||
*
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} x - X position of the new bitmapText object.
|
||||
* @param {number} y - Y position of the new bitmapText object.
|
||||
* @param {string} font - The key of the BitmapFont as stored in Game.Cache.
|
||||
* @param {string} [text=''] - The actual text that will be rendered. Can be set later via BitmapText.text.
|
||||
* @param {number} [size=32] - The size the font will be rendered in, in pixels.
|
||||
*/
|
||||
Phaser.BitmapText = function (game, x, y, font, text, size) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
font = font || '';
|
||||
text = text || '';
|
||||
size = size || 32;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this BitmapText.
|
||||
* @default
|
||||
*/
|
||||
this.name = '';
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @readonly
|
||||
*/
|
||||
this.type = Phaser.BITMAPTEXT;
|
||||
|
||||
/**
|
||||
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
|
||||
*/
|
||||
this.z = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
|
||||
*/
|
||||
this.world = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* @property {string} _text - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._text = text;
|
||||
|
||||
/**
|
||||
* @property {string} _font - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._font = font;
|
||||
|
||||
/**
|
||||
* @property {number} _fontSize - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._fontSize = size;
|
||||
|
||||
/**
|
||||
* @property {string} _align - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._align = 'left';
|
||||
|
||||
/**
|
||||
* @property {number} _tint - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._tint = 0xFFFFFF;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
|
||||
*/
|
||||
this.events = new Phaser.Events(this);
|
||||
|
||||
/**
|
||||
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
|
||||
*/
|
||||
this.cameraOffset = new Phaser.Point();
|
||||
|
||||
PIXI.BitmapText.call(this, text);
|
||||
|
||||
this.position.set(x, y);
|
||||
|
||||
/**
|
||||
* A small internal cache:
|
||||
* 0 = previous position.x
|
||||
* 1 = previous position.y
|
||||
* 2 = previous rotation
|
||||
* 3 = renderID
|
||||
* 4 = fresh? (0 = no, 1 = yes)
|
||||
* 5 = outOfBoundsFired (0 = no, 1 = yes)
|
||||
* 6 = exists (0 = no, 1 = yes)
|
||||
* 7 = fixed to camera (0 = no, 1 = yes)
|
||||
* 8 = destroy phase? (0 = no, 1 = yes)
|
||||
* @property {Array} _cache
|
||||
* @private
|
||||
*/
|
||||
this._cache = [0, 0, 0, 0, 1, 0, 1, 0, 0];
|
||||
|
||||
};
|
||||
|
||||
Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype);
|
||||
Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
|
||||
|
||||
/**
|
||||
* @method Phaser.BitmapText.prototype.setStyle
|
||||
* @private
|
||||
*/
|
||||
Phaser.BitmapText.prototype.setStyle = function() {
|
||||
|
||||
this.style = { align: this._align };
|
||||
this.fontName = this._font;
|
||||
this.fontSize = this._fontSize;
|
||||
this.dirty = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Automatically called by World.preUpdate.
|
||||
* @method Phaser.BitmapText.prototype.preUpdate
|
||||
*/
|
||||
Phaser.BitmapText.prototype.preUpdate = function () {
|
||||
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (!this.exists || !this.parent.exists)
|
||||
{
|
||||
this.renderOrderID = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.autoCull)
|
||||
{
|
||||
// Won't get rendered but will still get its transform updated
|
||||
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
|
||||
}
|
||||
|
||||
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
|
||||
|
||||
if (this.visible)
|
||||
{
|
||||
this._cache[3] = this.game.stage.currentRenderOrderID++;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Override and use this function in your own custom objects to handle any update requirements you may have.
|
||||
*
|
||||
* @method Phaser.BitmapText.prototype.update
|
||||
*/
|
||||
Phaser.BitmapText.prototype.update = function() {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Automatically called by World.postUpdate.
|
||||
* @method Phaser.BitmapText.prototype.postUpdate
|
||||
*/
|
||||
Phaser.BitmapText.prototype.postUpdate = function () {
|
||||
|
||||
// Fixed to Camera?
|
||||
if (this._cache[7] === 1)
|
||||
{
|
||||
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
|
||||
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroy this BitmapText instance. This will remove any filters and un-parent any children.
|
||||
* @method Phaser.BitmapText.prototype.destroy
|
||||
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
|
||||
*/
|
||||
Phaser.BitmapText.prototype.destroy = function(destroyChildren) {
|
||||
|
||||
if (this.game === null || this.destroyPhase) { return; }
|
||||
|
||||
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
|
||||
|
||||
this._cache[8] = 1;
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
if (this.parent instanceof Phaser.Group)
|
||||
{
|
||||
this.parent.remove(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.parent.removeChild(this);
|
||||
}
|
||||
}
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
if (destroyChildren)
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
if (this.children[i].destroy)
|
||||
{
|
||||
this.children[i].destroy(destroyChildren);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
this.filters = null;
|
||||
this.mask = null;
|
||||
this.game = null;
|
||||
|
||||
this._cache[8] = 0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#align
|
||||
* @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
|
||||
|
||||
get: function() {
|
||||
return this._align;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._align)
|
||||
{
|
||||
this._align = value;
|
||||
this.setStyle();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#tint
|
||||
* @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
|
||||
|
||||
get: function() {
|
||||
return this._tint;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._tint)
|
||||
{
|
||||
this._tint = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
|
||||
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
|
||||
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
|
||||
* @name Phaser.BitmapText#angle
|
||||
* @property {number} angle - Gets or sets the angle of rotation in degrees.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'angle', {
|
||||
|
||||
get: function() {
|
||||
return Phaser.Math.radToDeg(this.rotation);
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
this.rotation = Phaser.Math.degToRad(value);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#font
|
||||
* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
|
||||
|
||||
get: function() {
|
||||
return this._font;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._font)
|
||||
{
|
||||
this._font = value.trim();
|
||||
this.style.font = this._fontSize + "px '" + this._font + "'";
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#fontSize
|
||||
* @property {number} fontSize - The size of the font in pixels.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
|
||||
|
||||
get: function() {
|
||||
return this._fontSize;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
value = parseInt(value, 10);
|
||||
|
||||
if (value !== this._fontSize)
|
||||
{
|
||||
this._fontSize = value;
|
||||
this.style.font = this._fontSize + "px '" + this._font + "'";
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The text string to be displayed by this Text object, taking into account the style settings.
|
||||
* @name Phaser.BitmapText#text
|
||||
* @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
|
||||
|
||||
get: function() {
|
||||
return this._text;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._text)
|
||||
{
|
||||
this._text = value.toString() || ' ';
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
|
||||
* activated for this object and it will then start to process click/touch events and more.
|
||||
*
|
||||
* @name Phaser.BitmapText#inputEnabled
|
||||
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, "inputEnabled", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return (this.input && this.input.enabled);
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (this.input === null)
|
||||
{
|
||||
this.input = new Phaser.InputHandler(this);
|
||||
this.input.start();
|
||||
}
|
||||
else if (this.input && !this.input.enabled)
|
||||
{
|
||||
this.input.start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.input && this.input.enabled)
|
||||
{
|
||||
this.input.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* An BitmapText that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in BitmapText.cameraOffset.
|
||||
* Note that the cameraOffset values are in addition to any parent in the display list.
|
||||
* So if this BitmapText was in a Group that has x: 200, then this will be added to the cameraOffset.x
|
||||
*
|
||||
* @name Phaser.BitmapText#fixedToCamera
|
||||
* @property {boolean} fixedToCamera - Set to true to fix this BitmapText to the Camera at its current world coordinates.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, "fixedToCamera", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[7];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
this._cache[7] = 1;
|
||||
this.cameraOffset.set(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._cache[7] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#destroyPhase
|
||||
* @property {boolean} destroyPhase - True if this object is currently being destroyed.
|
||||
*/
|
||||
Object.defineProperty(Phaser.BitmapText.prototype, "destroyPhase", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[8];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
649
src/gameobjects/Button.js
Normal file
649
src/gameobjects/Button.js
Normal file
@@ -0,0 +1,649 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Button
|
||||
*
|
||||
* @classdesc Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are:
|
||||
*
|
||||
* * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
|
||||
* * 'Out' - when the Pointer that was previously over the Button moves out of it.
|
||||
* * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
|
||||
* * 'Up' - when the Pointer that was pressed down on the Button is released again.
|
||||
*
|
||||
* You can set a unique texture frame and Sound for any of these states.
|
||||
*
|
||||
* @constructor
|
||||
* @extends Phaser.Image
|
||||
*
|
||||
* @param {Phaser.Game} game Current game instance.
|
||||
* @param {number} [x=0] - X position of the Button.
|
||||
* @param {number} [y=0] - Y position of the Button.
|
||||
* @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this Button.
|
||||
* @param {function} [callback] - The function to call when this Button is pressed.
|
||||
* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
|
||||
* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
|
||||
*/
|
||||
Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
key = key || null;
|
||||
callback = callback || null;
|
||||
callbackContext = callbackContext || this;
|
||||
|
||||
Phaser.Image.call(this, game, x, y, key, outFrame);
|
||||
|
||||
/**
|
||||
* @property {number} type - The Phaser Object Type.
|
||||
*/
|
||||
this.type = Phaser.BUTTON;
|
||||
|
||||
/**
|
||||
* @property {string} _onOverFrameName - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onOverFrameName = null;
|
||||
|
||||
/**
|
||||
* @property {string} _onOutFrameName - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onOutFrameName = null;
|
||||
|
||||
/**
|
||||
* @property {string} _onDownFrameName - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onDownFrameName = null;
|
||||
|
||||
/**
|
||||
* @property {string} _onUpFrameName - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onUpFrameName = null;
|
||||
|
||||
/**
|
||||
* @property {number} _onOverFrameID - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onOverFrameID = null;
|
||||
|
||||
/**
|
||||
* @property {number} _onOutFrameID - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onOutFrameID = null;
|
||||
|
||||
/**
|
||||
* @property {number} _onDownFrameID - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onDownFrameID = null;
|
||||
|
||||
/**
|
||||
* @property {number} _onUpFrameID - Internal variable.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onUpFrameID = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} onOverMouseOnly - If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer.
|
||||
* @default
|
||||
*/
|
||||
this.onOverMouseOnly = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sound} onOverSound - The Sound to be played when this Buttons Over state is activated.
|
||||
* @default
|
||||
*/
|
||||
this.onOverSound = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sound} onOutSound - The Sound to be played when this Buttons Out state is activated.
|
||||
* @default
|
||||
*/
|
||||
this.onOutSound = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sound} onDownSound - The Sound to be played when this Buttons Down state is activated.
|
||||
* @default
|
||||
*/
|
||||
this.onDownSound = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sound} onUpSound - The Sound to be played when this Buttons Up state is activated.
|
||||
* @default
|
||||
*/
|
||||
this.onUpSound = null;
|
||||
|
||||
/**
|
||||
* @property {string} onOverSoundMarker - The Sound Marker used in conjunction with the onOverSound.
|
||||
* @default
|
||||
*/
|
||||
this.onOverSoundMarker = '';
|
||||
|
||||
/**
|
||||
* @property {string} onOutSoundMarker - The Sound Marker used in conjunction with the onOutSound.
|
||||
* @default
|
||||
*/
|
||||
this.onOutSoundMarker = '';
|
||||
|
||||
/**
|
||||
* @property {string} onDownSoundMarker - The Sound Marker used in conjunction with the onDownSound.
|
||||
* @default
|
||||
*/
|
||||
this.onDownSoundMarker = '';
|
||||
|
||||
/**
|
||||
* @property {string} onUpSoundMarker - The Sound Marker used in conjunction with the onUpSound.
|
||||
* @default
|
||||
*/
|
||||
this.onUpSoundMarker = '';
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onInputOver - The Signal (or event) dispatched when this Button is in an Over state.
|
||||
*/
|
||||
this.onInputOver = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onInputOut - The Signal (or event) dispatched when this Button is in an Out state.
|
||||
*/
|
||||
this.onInputOut = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onInputDown - The Signal (or event) dispatched when this Button is in an Down state.
|
||||
*/
|
||||
this.onInputDown = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onInputUp - The Signal (or event) dispatched when this Button is in an Up state.
|
||||
*/
|
||||
this.onInputUp = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {boolean} freezeFrames - When true the Button will cease to change texture frame on all events (over, out, up, down).
|
||||
*/
|
||||
this.freezeFrames = false;
|
||||
|
||||
/**
|
||||
* When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
|
||||
* @property {boolean} forceOut
|
||||
* @default
|
||||
*/
|
||||
this.forceOut = false;
|
||||
|
||||
this.inputEnabled = true;
|
||||
|
||||
this.input.start(0, true);
|
||||
|
||||
this.setFrames(overFrame, outFrame, downFrame, upFrame);
|
||||
|
||||
if (callback !== null)
|
||||
{
|
||||
this.onInputUp.add(callback, callbackContext);
|
||||
}
|
||||
|
||||
// Redirect the input events to here so we can handle animation updates, etc
|
||||
this.events.onInputOver.add(this.onInputOverHandler, this);
|
||||
this.events.onInputOut.add(this.onInputOutHandler, this);
|
||||
this.events.onInputDown.add(this.onInputDownHandler, this);
|
||||
this.events.onInputUp.add(this.onInputUpHandler, this);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
|
||||
Phaser.Button.prototype.constructor = Phaser.Button;
|
||||
|
||||
/**
|
||||
* Clears all of the frames set on this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.clearFrames
|
||||
*/
|
||||
Phaser.Button.prototype.clearFrames = function () {
|
||||
|
||||
this._onOverFrameName = null;
|
||||
this._onOverFrameID = null;
|
||||
|
||||
this._onOutFrameName = null;
|
||||
this._onOutFrameID = null;
|
||||
|
||||
this._onDownFrameName = null;
|
||||
this._onDownFrameID = null;
|
||||
|
||||
this._onUpFrameName = null;
|
||||
this._onUpFrameID = null;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Used to manually set the frames that will be used for the different states of the Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setFrames
|
||||
* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
|
||||
*/
|
||||
Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
|
||||
|
||||
this.clearFrames();
|
||||
|
||||
if (overFrame !== null)
|
||||
{
|
||||
if (typeof overFrame === 'string')
|
||||
{
|
||||
this._onOverFrameName = overFrame;
|
||||
|
||||
if (this.input.pointerOver())
|
||||
{
|
||||
this.frameName = overFrame;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._onOverFrameID = overFrame;
|
||||
|
||||
if (this.input.pointerOver())
|
||||
{
|
||||
this.frame = overFrame;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (outFrame !== null)
|
||||
{
|
||||
if (typeof outFrame === 'string')
|
||||
{
|
||||
this._onOutFrameName = outFrame;
|
||||
|
||||
if (this.input.pointerOver() === false)
|
||||
{
|
||||
this.frameName = outFrame;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._onOutFrameID = outFrame;
|
||||
|
||||
if (this.input.pointerOver() === false)
|
||||
{
|
||||
this.frame = outFrame;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (downFrame !== null)
|
||||
{
|
||||
if (typeof downFrame === 'string')
|
||||
{
|
||||
this._onDownFrameName = downFrame;
|
||||
|
||||
if (this.input.pointerDown())
|
||||
{
|
||||
this.frameName = downFrame;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._onDownFrameID = downFrame;
|
||||
|
||||
if (this.input.pointerDown())
|
||||
{
|
||||
this.frame = downFrame;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (upFrame !== null)
|
||||
{
|
||||
if (typeof upFrame === 'string')
|
||||
{
|
||||
this._onUpFrameName = upFrame;
|
||||
|
||||
if (this.input.pointerUp())
|
||||
{
|
||||
this.frameName = upFrame;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._onUpFrameID = upFrame;
|
||||
|
||||
if (this.input.pointerUp())
|
||||
{
|
||||
this.frame = upFrame;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object.
|
||||
* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
|
||||
* Call this function with no parameters at all to reset all sounds on this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setSounds
|
||||
* @param {Phaser.Sound} [overSound] - Over Button Sound.
|
||||
* @param {string} [overMarker] - Over Button Sound Marker.
|
||||
* @param {Phaser.Sound} [downSound] - Down Button Sound.
|
||||
* @param {string} [downMarker] - Down Button Sound Marker.
|
||||
* @param {Phaser.Sound} [outSound] - Out Button Sound.
|
||||
* @param {string} [outMarker] - Out Button Sound Marker.
|
||||
* @param {Phaser.Sound} [upSound] - Up Button Sound.
|
||||
* @param {string} [upMarker] - Up Button Sound Marker.
|
||||
*/
|
||||
Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
|
||||
|
||||
this.setOverSound(overSound, overMarker);
|
||||
this.setOutSound(outSound, outMarker);
|
||||
this.setDownSound(downSound, downMarker);
|
||||
this.setUpSound(upSound, upMarker);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* The Sound to be played when a Pointer moves over this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setOverSound
|
||||
* @param {Phaser.Sound} sound - The Sound that will be played.
|
||||
* @param {string} [marker] - A Sound Marker that will be used in the playback.
|
||||
*/
|
||||
Phaser.Button.prototype.setOverSound = function (sound, marker) {
|
||||
|
||||
this.onOverSound = null;
|
||||
this.onOverSoundMarker = '';
|
||||
|
||||
if (sound instanceof Phaser.Sound)
|
||||
{
|
||||
this.onOverSound = sound;
|
||||
}
|
||||
|
||||
if (typeof marker === 'string')
|
||||
{
|
||||
this.onOverSoundMarker = marker;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* The Sound to be played when a Pointer moves out of this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setOutSound
|
||||
* @param {Phaser.Sound} sound - The Sound that will be played.
|
||||
* @param {string} [marker] - A Sound Marker that will be used in the playback.
|
||||
*/
|
||||
Phaser.Button.prototype.setOutSound = function (sound, marker) {
|
||||
|
||||
this.onOutSound = null;
|
||||
this.onOutSoundMarker = '';
|
||||
|
||||
if (sound instanceof Phaser.Sound)
|
||||
{
|
||||
this.onOutSound = sound;
|
||||
}
|
||||
|
||||
if (typeof marker === 'string')
|
||||
{
|
||||
this.onOutSoundMarker = marker;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* The Sound to be played when a Pointer presses down on this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setDownSound
|
||||
* @param {Phaser.Sound} sound - The Sound that will be played.
|
||||
* @param {string} [marker] - A Sound Marker that will be used in the playback.
|
||||
*/
|
||||
Phaser.Button.prototype.setDownSound = function (sound, marker) {
|
||||
|
||||
this.onDownSound = null;
|
||||
this.onDownSoundMarker = '';
|
||||
|
||||
if (sound instanceof Phaser.Sound)
|
||||
{
|
||||
this.onDownSound = sound;
|
||||
}
|
||||
|
||||
if (typeof marker === 'string')
|
||||
{
|
||||
this.onDownSoundMarker = marker;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* The Sound to be played when a Pointer has pressed down and is released from this Button.
|
||||
*
|
||||
* @method Phaser.Button.prototype.setUpSound
|
||||
* @param {Phaser.Sound} sound - The Sound that will be played.
|
||||
* @param {string} [marker] - A Sound Marker that will be used in the playback.
|
||||
*/
|
||||
Phaser.Button.prototype.setUpSound = function (sound, marker) {
|
||||
|
||||
this.onUpSound = null;
|
||||
this.onUpSoundMarker = '';
|
||||
|
||||
if (sound instanceof Phaser.Sound)
|
||||
{
|
||||
this.onUpSound = sound;
|
||||
}
|
||||
|
||||
if (typeof marker === 'string')
|
||||
{
|
||||
this.onUpSoundMarker = marker;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that handles input events.
|
||||
*
|
||||
* @protected
|
||||
* @method Phaser.Button.prototype.onInputOverHandler
|
||||
* @param {Phaser.Button} sprite - The Button that the event occured on.
|
||||
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
|
||||
*/
|
||||
Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
|
||||
|
||||
if (this.freezeFrames === false)
|
||||
{
|
||||
this.setState(1);
|
||||
}
|
||||
|
||||
if (this.onOverMouseOnly && !pointer.isMouse)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.onOverSound)
|
||||
{
|
||||
this.onOverSound.play(this.onOverSoundMarker);
|
||||
}
|
||||
|
||||
if (this.onInputOver)
|
||||
{
|
||||
this.onInputOver.dispatch(this, pointer);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that handles input events.
|
||||
*
|
||||
* @protected
|
||||
* @method Phaser.Button.prototype.onInputOutHandler
|
||||
* @param {Phaser.Button} sprite - The Button that the event occured on.
|
||||
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
|
||||
*/
|
||||
Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
|
||||
|
||||
if (this.freezeFrames === false)
|
||||
{
|
||||
this.setState(2);
|
||||
}
|
||||
|
||||
if (this.onOutSound)
|
||||
{
|
||||
this.onOutSound.play(this.onOutSoundMarker);
|
||||
}
|
||||
|
||||
if (this.onInputOut)
|
||||
{
|
||||
this.onInputOut.dispatch(this, pointer);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that handles input events.
|
||||
*
|
||||
* @protected
|
||||
* @method Phaser.Button.prototype.onInputDownHandler
|
||||
* @param {Phaser.Button} sprite - The Button that the event occured on.
|
||||
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
|
||||
*/
|
||||
Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
|
||||
|
||||
if (this.freezeFrames === false)
|
||||
{
|
||||
this.setState(3);
|
||||
}
|
||||
|
||||
if (this.onDownSound)
|
||||
{
|
||||
this.onDownSound.play(this.onDownSoundMarker);
|
||||
}
|
||||
|
||||
if (this.onInputDown)
|
||||
{
|
||||
this.onInputDown.dispatch(this, pointer);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that handles input events.
|
||||
*
|
||||
* @protected
|
||||
* @method Phaser.Button.prototype.onInputUpHandler
|
||||
* @param {Phaser.Button} sprite - The Button that the event occured on.
|
||||
* @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
|
||||
*/
|
||||
Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
|
||||
|
||||
if (this.onUpSound)
|
||||
{
|
||||
this.onUpSound.play(this.onUpSoundMarker);
|
||||
}
|
||||
|
||||
if (this.onInputUp)
|
||||
{
|
||||
this.onInputUp.dispatch(this, pointer, isOver);
|
||||
}
|
||||
|
||||
if (this.freezeFrames)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.forceOut)
|
||||
{
|
||||
// Button should be forced to the Out frame when released.
|
||||
this.setState(2);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this._onUpFrameName !== null || this._onUpFrameID !== null)
|
||||
{
|
||||
this.setState(4);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (isOver)
|
||||
{
|
||||
this.setState(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.setState(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that handles Button state changes.
|
||||
*
|
||||
* @protected
|
||||
* @method Phaser.Button.prototype.setState
|
||||
* @param {number} newState - The new State of the Button.
|
||||
*/
|
||||
Phaser.Button.prototype.setState = function (newState) {
|
||||
|
||||
if (newState === 1)
|
||||
{
|
||||
// Over
|
||||
if (this._onOverFrameName != null)
|
||||
{
|
||||
this.frameName = this._onOverFrameName;
|
||||
}
|
||||
else if (this._onOverFrameID != null)
|
||||
{
|
||||
this.frame = this._onOverFrameID;
|
||||
}
|
||||
}
|
||||
else if (newState === 2)
|
||||
{
|
||||
// Out
|
||||
if (this._onOutFrameName != null)
|
||||
{
|
||||
this.frameName = this._onOutFrameName;
|
||||
}
|
||||
else if (this._onOutFrameID != null)
|
||||
{
|
||||
this.frame = this._onOutFrameID;
|
||||
}
|
||||
}
|
||||
else if (newState === 3)
|
||||
{
|
||||
// Down
|
||||
if (this._onDownFrameName != null)
|
||||
{
|
||||
this.frameName = this._onDownFrameName;
|
||||
}
|
||||
else if (this._onDownFrameID != null)
|
||||
{
|
||||
this.frame = this._onDownFrameID;
|
||||
}
|
||||
}
|
||||
else if (newState === 4)
|
||||
{
|
||||
// Up
|
||||
if (this._onUpFrameName != null)
|
||||
{
|
||||
this.frameName = this._onUpFrameName;
|
||||
}
|
||||
else if (this._onUpFrameID != null)
|
||||
{
|
||||
this.frame = this._onUpFrameID;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
80
src/gameobjects/Events.js
Normal file
80
src/gameobjects/Events.js
Normal file
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Events
|
||||
*
|
||||
* @classdesc The Events component is a collection of events fired by the parent game object.
|
||||
*
|
||||
* For example to tell when a Sprite has been added to a new group:
|
||||
*
|
||||
* `sprite.events.onAddedToGroup.add(yourFunction, this);`
|
||||
*
|
||||
* Where `yourFunction` is the function you want called when this event occurs.
|
||||
*
|
||||
* Note that the Input related events only exist if the Sprite has had `inputEnabled` set to `true`.
|
||||
*
|
||||
* @constructor
|
||||
*
|
||||
* @param {Phaser.Sprite} sprite - A reference to Description.
|
||||
*/
|
||||
Phaser.Events = function (sprite) {
|
||||
|
||||
this.parent = sprite;
|
||||
|
||||
this.onAddedToGroup = new Phaser.Signal();
|
||||
this.onRemovedFromGroup = new Phaser.Signal();
|
||||
this.onKilled = new Phaser.Signal();
|
||||
this.onRevived = new Phaser.Signal();
|
||||
this.onOutOfBounds = new Phaser.Signal();
|
||||
this.onEnterBounds = new Phaser.Signal();
|
||||
|
||||
this.onInputOver = null;
|
||||
this.onInputOut = null;
|
||||
this.onInputDown = null;
|
||||
this.onInputUp = null;
|
||||
this.onDragStart = null;
|
||||
this.onDragStop = null;
|
||||
|
||||
this.onAnimationStart = null;
|
||||
this.onAnimationComplete = null;
|
||||
this.onAnimationLoop = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Events.prototype = {
|
||||
|
||||
destroy: function () {
|
||||
|
||||
this.parent = null;
|
||||
this.onAddedToGroup.dispose();
|
||||
this.onRemovedFromGroup.dispose();
|
||||
this.onKilled.dispose();
|
||||
this.onRevived.dispose();
|
||||
this.onOutOfBounds.dispose();
|
||||
|
||||
if (this.onInputOver)
|
||||
{
|
||||
this.onInputOver.dispose();
|
||||
this.onInputOut.dispose();
|
||||
this.onInputDown.dispose();
|
||||
this.onInputUp.dispose();
|
||||
this.onDragStart.dispose();
|
||||
this.onDragStop.dispose();
|
||||
}
|
||||
|
||||
if (this.onAnimationStart)
|
||||
{
|
||||
this.onAnimationStart.dispose();
|
||||
this.onAnimationComplete.dispose();
|
||||
this.onAnimationLoop.dispose();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Events.prototype.constructor = Phaser.Events;
|
||||
366
src/gameobjects/GameObjectCreator.js
Normal file
366
src/gameobjects/GameObjectCreator.js
Normal file
@@ -0,0 +1,366 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Game Object Creator is a quick way to create all of the different sorts of core objects that Phaser uses, but not add them to the game world.
|
||||
* Use the GameObjectFactory to create and add the objects into the world.
|
||||
*
|
||||
* @class Phaser.GameObjectCreator
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.GameObjectCreator = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.World} world - A reference to the game world.
|
||||
*/
|
||||
this.world = this.game.world;
|
||||
|
||||
};
|
||||
|
||||
Phaser.GameObjectCreator.prototype = {
|
||||
|
||||
/**
|
||||
* Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
|
||||
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#image
|
||||
* @param {number} x - X position of the image.
|
||||
* @param {number} y - Y position of the image.
|
||||
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
|
||||
* @returns {Phaser.Sprite} the newly created sprite object.
|
||||
*/
|
||||
image: function (x, y, key, frame) {
|
||||
|
||||
return new Phaser.Image(this.game, x, y, key, frame);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new Sprite with specific position and sprite sheet key.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#sprite
|
||||
* @param {number} x - X position of the new sprite.
|
||||
* @param {number} y - Y position of the new sprite.
|
||||
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
|
||||
* @returns {Phaser.Sprite} the newly created sprite object.
|
||||
*/
|
||||
sprite: function (x, y, key, frame) {
|
||||
|
||||
return new Phaser.Sprite(this.game, x, y, key, frame);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#tween
|
||||
* @param {object} obj - Object the tween will be run on.
|
||||
* @return {Phaser.Tween} The Tween object.
|
||||
*/
|
||||
tween: function (obj) {
|
||||
|
||||
return new Phaser.Tween(obj, this.game);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#group
|
||||
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
* @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
|
||||
* @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
|
||||
* @return {Phaser.Group} The newly created group.
|
||||
*/
|
||||
group: function (parent, name, addToStage, enableBody, physicsBodyType) {
|
||||
|
||||
return new Phaser.Group(this.game, null, name, addToStage, enableBody, physicsBodyType);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#spriteBatch
|
||||
* @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
|
||||
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
* @return {Phaser.Group} The newly created group.
|
||||
*/
|
||||
spriteBatch: function (parent, name, addToStage) {
|
||||
|
||||
if (typeof name === 'undefined') { name = 'group'; }
|
||||
if (typeof addToStage === 'undefined') { addToStage = false; }
|
||||
|
||||
return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Sound object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#audio
|
||||
* @param {string} key - The Game.cache key of the sound that this object will use.
|
||||
* @param {number} [volume=1] - The volume at which the sound will be played.
|
||||
* @param {boolean} [loop=false] - Whether or not the sound will loop.
|
||||
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
|
||||
* @return {Phaser.Sound} The newly created text object.
|
||||
*/
|
||||
audio: function (key, volume, loop, connect) {
|
||||
|
||||
return this.game.sound.add(key, volume, loop, connect);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Sound object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#sound
|
||||
* @param {string} key - The Game.cache key of the sound that this object will use.
|
||||
* @param {number} [volume=1] - The volume at which the sound will be played.
|
||||
* @param {boolean} [loop=false] - Whether or not the sound will loop.
|
||||
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
|
||||
* @return {Phaser.Sound} The newly created text object.
|
||||
*/
|
||||
sound: function (key, volume, loop, connect) {
|
||||
|
||||
return this.game.sound.add(key, volume, loop, connect);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new TileSprite object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#tileSprite
|
||||
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} width - The width of the TileSprite.
|
||||
* @param {number} height - The height of the TileSprite.
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
* @return {Phaser.TileSprite} The newly created tileSprite object.
|
||||
*/
|
||||
tileSprite: function (x, y, width, height, key, frame) {
|
||||
|
||||
return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Text object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#text
|
||||
* @param {number} x - X position of the new text object.
|
||||
* @param {number} y - Y position of the new text object.
|
||||
* @param {string} text - The actual text that will be written.
|
||||
* @param {object} style - The style object containing style attributes like font, font size , etc.
|
||||
* @return {Phaser.Text} The newly created text object.
|
||||
*/
|
||||
text: function (x, y, text, style) {
|
||||
|
||||
return new Phaser.Text(this.game, x, y, text, style);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Button object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#button
|
||||
* @param {number} [x] X position of the new button object.
|
||||
* @param {number} [y] Y position of the new button object.
|
||||
* @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
|
||||
* @param {function} [callback] The function to call when this button is pressed
|
||||
* @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
|
||||
* @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @return {Phaser.Button} The newly created button object.
|
||||
*/
|
||||
button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
|
||||
|
||||
return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Graphics object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#graphics
|
||||
* @param {number} x - X position of the new graphics object.
|
||||
* @param {number} y - Y position of the new graphics object.
|
||||
* @return {Phaser.Graphics} The newly created graphics object.
|
||||
*/
|
||||
graphics: function (x, y) {
|
||||
|
||||
return new Phaser.Graphics(this.game, x, y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
|
||||
* continuous effects like rain and fire. All it really does is launch Particle objects out
|
||||
* at set intervals, and fixes their positions and velocities accorindgly.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#emitter
|
||||
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [maxParticles=50] - The total number of particles in this emitter.
|
||||
* @return {Phaser.Emitter} The newly created emitter object.
|
||||
*/
|
||||
emitter: function (x, y, maxParticles) {
|
||||
|
||||
return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
|
||||
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
|
||||
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
|
||||
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
|
||||
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
|
||||
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#retroFont
|
||||
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
|
||||
* @param {number} characterWidth - The width of each character in the font set.
|
||||
* @param {number} characterHeight - The height of each character in the font set.
|
||||
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
|
||||
* @param {number} charsPerRow - The number of characters per row in the font set.
|
||||
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
|
||||
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
|
||||
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
|
||||
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
|
||||
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
|
||||
*/
|
||||
retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
|
||||
|
||||
return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new BitmapText object.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#bitmapText
|
||||
* @param {number} x - X position of the new bitmapText object.
|
||||
* @param {number} y - Y position of the new bitmapText object.
|
||||
* @param {string} font - The key of the BitmapText font as stored in Game.Cache.
|
||||
* @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
|
||||
* @param {number} [size] - The size the font will be rendered in, in pixels.
|
||||
* @return {Phaser.BitmapText} The newly created bitmapText object.
|
||||
*/
|
||||
bitmapText: function (x, y, font, text, size) {
|
||||
|
||||
return new Phaser.BitmapText(this.game, x, y, font, text, size);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
|
||||
* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
|
||||
* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
|
||||
* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
|
||||
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#tilemap
|
||||
* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
|
||||
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
|
||||
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
|
||||
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
|
||||
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
|
||||
*/
|
||||
tilemap: function (key, tileWidth, tileHeight, width, height) {
|
||||
|
||||
return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A dynamic initially blank canvas to which images can be drawn.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#renderTexture
|
||||
* @param {number} [width=100] - the width of the RenderTexture.
|
||||
* @param {number} [height=100] - the height of the RenderTexture.
|
||||
* @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
|
||||
* @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
|
||||
* @return {Phaser.RenderTexture} The newly created RenderTexture object.
|
||||
*/
|
||||
renderTexture: function (width, height, key, addToCache) {
|
||||
|
||||
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
|
||||
if (typeof addToCache === 'undefined') { addToCache = false; }
|
||||
|
||||
var texture = new Phaser.RenderTexture(this.game, width, height, key);
|
||||
|
||||
if (addToCache)
|
||||
{
|
||||
this.game.cache.addRenderTexture(key, texture);
|
||||
}
|
||||
|
||||
return texture;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#bitmapData
|
||||
* @param {number} [width=100] - The width of the BitmapData in pixels.
|
||||
* @param {number} [height=100] - The height of the BitmapData in pixels.
|
||||
* @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
|
||||
* @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
|
||||
* @return {Phaser.BitmapData} The newly created BitmapData object.
|
||||
*/
|
||||
bitmapData: function (width, height, key, addToCache) {
|
||||
|
||||
if (typeof addToCache === 'undefined') { addToCache = false; }
|
||||
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
|
||||
|
||||
var texture = new Phaser.BitmapData(this.game, key, width, height);
|
||||
|
||||
if (addToCache)
|
||||
{
|
||||
this.game.cache.addBitmapData(key, texture);
|
||||
}
|
||||
|
||||
return texture;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A WebGL shader/filter that can be applied to Sprites.
|
||||
*
|
||||
* @method Phaser.GameObjectCreator#filter
|
||||
* @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
|
||||
* @param {any} - Whatever parameters are needed to be passed to the filter init function.
|
||||
* @return {Phaser.Filter} The newly created Phaser.Filter object.
|
||||
*/
|
||||
filter: function (filter) {
|
||||
|
||||
var args = Array.prototype.splice.call(arguments, 1);
|
||||
|
||||
var filter = new Phaser.Filter[filter](this.game);
|
||||
|
||||
filter.init.apply(filter, args);
|
||||
|
||||
return filter;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
|
||||
418
src/gameobjects/GameObjectFactory.js
Normal file
418
src/gameobjects/GameObjectFactory.js
Normal file
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses.
|
||||
*
|
||||
* @class Phaser.GameObjectFactory
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.GameObjectFactory = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.World} world - A reference to the game world.
|
||||
*/
|
||||
this.world = this.game.world;
|
||||
|
||||
};
|
||||
|
||||
Phaser.GameObjectFactory.prototype = {
|
||||
|
||||
/**
|
||||
* Adds an existing object to the game world.
|
||||
* @method Phaser.GameObjectFactory#existing
|
||||
* @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object..
|
||||
* @return {*} The child that was added to the Group.
|
||||
*/
|
||||
existing: function (object) {
|
||||
|
||||
return this.world.add(object);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
|
||||
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#image
|
||||
* @param {number} x - X position of the image.
|
||||
* @param {number} y - Y position of the image.
|
||||
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @returns {Phaser.Sprite} the newly created sprite object.
|
||||
*/
|
||||
image: function (x, y, key, frame, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.Image(this.game, x, y, key, frame));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new Sprite with specific position and sprite sheet key.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#sprite
|
||||
* @param {number} x - X position of the new sprite.
|
||||
* @param {number} y - Y position of the new sprite.
|
||||
* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @returns {Phaser.Sprite} the newly created sprite object.
|
||||
*/
|
||||
sprite: function (x, y, key, frame, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.create(x, y, key, frame);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#tween
|
||||
* @param {object} obj - Object the tween will be run on.
|
||||
* @return {Phaser.Tween} The newly created Phaser.Tween object.
|
||||
*/
|
||||
tween: function (obj) {
|
||||
|
||||
return this.game.tweens.create(obj);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#group
|
||||
* @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
|
||||
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
* @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
|
||||
* @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
|
||||
* @return {Phaser.Group} The newly created group.
|
||||
*/
|
||||
group: function (parent, name, addToStage, enableBody, physicsBodyType) {
|
||||
|
||||
return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
|
||||
* A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
|
||||
* are automatically given a physics body.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#group
|
||||
* @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
|
||||
* @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
|
||||
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
* @return {Phaser.Group} The newly created group.
|
||||
*/
|
||||
physicsGroup: function (physicsBodyType, parent, name, addToStage) {
|
||||
|
||||
return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#spriteBatch
|
||||
* @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
|
||||
* @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
* @return {Phaser.Group} The newly created group.
|
||||
*/
|
||||
spriteBatch: function (parent, name, addToStage) {
|
||||
|
||||
if (typeof name === 'undefined') { name = 'group'; }
|
||||
if (typeof addToStage === 'undefined') { addToStage = false; }
|
||||
|
||||
return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Sound object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#audio
|
||||
* @param {string} key - The Game.cache key of the sound that this object will use.
|
||||
* @param {number} [volume=1] - The volume at which the sound will be played.
|
||||
* @param {boolean} [loop=false] - Whether or not the sound will loop.
|
||||
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
|
||||
* @return {Phaser.Sound} The newly created text object.
|
||||
*/
|
||||
audio: function (key, volume, loop, connect) {
|
||||
|
||||
return this.game.sound.add(key, volume, loop, connect);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Sound object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#sound
|
||||
* @param {string} key - The Game.cache key of the sound that this object will use.
|
||||
* @param {number} [volume=1] - The volume at which the sound will be played.
|
||||
* @param {boolean} [loop=false] - Whether or not the sound will loop.
|
||||
* @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
|
||||
* @return {Phaser.Sound} The newly created text object.
|
||||
*/
|
||||
sound: function (key, volume, loop, connect) {
|
||||
|
||||
return this.game.sound.add(key, volume, loop, connect);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new TileSprite object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#tileSprite
|
||||
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} width - The width of the TileSprite.
|
||||
* @param {number} height - The height of the TileSprite.
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @return {Phaser.TileSprite} The newly created tileSprite object.
|
||||
*/
|
||||
tileSprite: function (x, y, width, height, key, frame, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Text object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#text
|
||||
* @param {number} x - X position of the new text object.
|
||||
* @param {number} y - Y position of the new text object.
|
||||
* @param {string} text - The actual text that will be written.
|
||||
* @param {object} style - The style object containing style attributes like font, font size , etc.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @return {Phaser.Text} The newly created text object.
|
||||
*/
|
||||
text: function (x, y, text, style, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.Text(this.game, x, y, text, style));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Button object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#button
|
||||
* @param {number} [x] X position of the new button object.
|
||||
* @param {number} [y] Y position of the new button object.
|
||||
* @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
|
||||
* @param {function} [callback] The function to call when this button is pressed
|
||||
* @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
|
||||
* @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @return {Phaser.Button} The newly created button object.
|
||||
*/
|
||||
button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Graphics object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#graphics
|
||||
* @param {number} x - X position of the new graphics object.
|
||||
* @param {number} y - Y position of the new graphics object.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @return {Phaser.Graphics} The newly created graphics object.
|
||||
*/
|
||||
graphics: function (x, y, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.Graphics(this.game, x, y));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
|
||||
* continuous effects like rain and fire. All it really does is launch Particle objects out
|
||||
* at set intervals, and fixes their positions and velocities accorindgly.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#emitter
|
||||
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [maxParticles=50] - The total number of particles in this emitter.
|
||||
* @return {Phaser.Emitter} The newly created emitter object.
|
||||
*/
|
||||
emitter: function (x, y, maxParticles) {
|
||||
|
||||
return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new RetroFont object to be used as a texture for an Image or Sprite and optionally add it to the Cache.
|
||||
* A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
|
||||
* If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
|
||||
* is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
|
||||
* The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
|
||||
* i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#retroFont
|
||||
* @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
|
||||
* @param {number} characterWidth - The width of each character in the font set.
|
||||
* @param {number} characterHeight - The height of each character in the font set.
|
||||
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
|
||||
* @param {number} charsPerRow - The number of characters per row in the font set.
|
||||
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
|
||||
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
|
||||
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
|
||||
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
|
||||
* @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
|
||||
*/
|
||||
retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
|
||||
|
||||
return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a new BitmapText object.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#bitmapText
|
||||
* @param {number} x - X position of the new bitmapText object.
|
||||
* @param {number} y - Y position of the new bitmapText object.
|
||||
* @param {string} font - The key of the BitmapText font as stored in Game.Cache.
|
||||
* @param {string} [text] - The actual text that will be rendered. Can be set later via BitmapText.text.
|
||||
* @param {number} [size] - The size the font will be rendered in, in pixels.
|
||||
* @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
|
||||
* @return {Phaser.BitmapText} The newly created bitmapText object.
|
||||
*/
|
||||
bitmapText: function (x, y, font, text, size, group) {
|
||||
|
||||
if (typeof group === 'undefined') { group = this.world; }
|
||||
|
||||
return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
|
||||
* To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
|
||||
* When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
|
||||
* If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
|
||||
* Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#tilemap
|
||||
* @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
|
||||
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
|
||||
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
|
||||
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
|
||||
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
|
||||
* @return {Phaser.Tilemap} The newly created tilemap object.
|
||||
*/
|
||||
tilemap: function (key, tileWidth, tileHeight, width, height) {
|
||||
|
||||
return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A dynamic initially blank canvas to which images can be drawn.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#renderTexture
|
||||
* @param {number} [width=100] - the width of the RenderTexture.
|
||||
* @param {number} [height=100] - the height of the RenderTexture.
|
||||
* @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
|
||||
* @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
|
||||
* @return {Phaser.RenderTexture} The newly created RenderTexture object.
|
||||
*/
|
||||
renderTexture: function (width, height, key, addToCache) {
|
||||
|
||||
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
|
||||
if (typeof addToCache === 'undefined') { addToCache = false; }
|
||||
|
||||
var texture = new Phaser.RenderTexture(this.game, width, height, key);
|
||||
|
||||
if (addToCache)
|
||||
{
|
||||
this.game.cache.addRenderTexture(key, texture);
|
||||
}
|
||||
|
||||
return texture;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#bitmapData
|
||||
* @param {number} [width=100] - The width of the BitmapData in pixels.
|
||||
* @param {number} [height=100] - The height of the BitmapData in pixels.
|
||||
* @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
|
||||
* @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
|
||||
* @return {Phaser.BitmapData} The newly created BitmapData object.
|
||||
*/
|
||||
bitmapData: function (width, height, key, addToCache) {
|
||||
|
||||
if (typeof addToCache === 'undefined') { addToCache = false; }
|
||||
if (typeof key === 'undefined' || key === '') { key = this.game.rnd.uuid(); }
|
||||
|
||||
var texture = new Phaser.BitmapData(this.game, key, width, height);
|
||||
|
||||
if (addToCache)
|
||||
{
|
||||
this.game.cache.addBitmapData(key, texture);
|
||||
}
|
||||
|
||||
return texture;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A WebGL shader/filter that can be applied to Sprites.
|
||||
*
|
||||
* @method Phaser.GameObjectFactory#filter
|
||||
* @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
|
||||
* @param {any} - Whatever parameters are needed to be passed to the filter init function.
|
||||
* @return {Phaser.Filter} The newly created Phaser.Filter object.
|
||||
*/
|
||||
filter: function (filter) {
|
||||
|
||||
var args = Array.prototype.splice.call(arguments, 1);
|
||||
|
||||
var filter = new Phaser.Filter[filter](this.game);
|
||||
|
||||
filter.init.apply(filter, args);
|
||||
|
||||
return filter;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
|
||||
386
src/gameobjects/Graphics.js
Normal file
386
src/gameobjects/Graphics.js
Normal file
@@ -0,0 +1,386 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new `Graphics` object.
|
||||
*
|
||||
* @class Phaser.Graphics
|
||||
* @constructor
|
||||
*
|
||||
* @param {Phaser.Game} game Current game instance.
|
||||
* @param {number} x - X position of the new graphics object.
|
||||
* @param {number} y - Y position of the new graphics object.
|
||||
*/
|
||||
Phaser.Graphics = function (game, x, y) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this object.
|
||||
* @default
|
||||
*/
|
||||
this.name = '';
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @default
|
||||
*/
|
||||
this.type = Phaser.GRAPHICS;
|
||||
|
||||
/**
|
||||
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
|
||||
*/
|
||||
this.z = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
|
||||
*/
|
||||
this.world = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
|
||||
*/
|
||||
this.cameraOffset = new Phaser.Point();
|
||||
|
||||
PIXI.Graphics.call(this);
|
||||
|
||||
this.position.set(x, y);
|
||||
|
||||
/**
|
||||
* A small internal cache:
|
||||
* 0 = previous position.x
|
||||
* 1 = previous position.y
|
||||
* 2 = previous rotation
|
||||
* 3 = renderID
|
||||
* 4 = fresh? (0 = no, 1 = yes)
|
||||
* 5 = outOfBoundsFired (0 = no, 1 = yes)
|
||||
* 6 = exists (0 = no, 1 = yes)
|
||||
* 7 = fixed to camera (0 = no, 1 = yes)
|
||||
* 8 = destroy phase? (0 = no, 1 = yes)
|
||||
* @property {Array} _cache
|
||||
* @private
|
||||
*/
|
||||
this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
|
||||
|
||||
};
|
||||
|
||||
Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
|
||||
Phaser.Graphics.prototype.constructor = Phaser.Graphics;
|
||||
|
||||
/**
|
||||
* Automatically called by World.preUpdate.
|
||||
* @method Phaser.Graphics.prototype.preUpdate
|
||||
*/
|
||||
Phaser.Graphics.prototype.preUpdate = function () {
|
||||
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (!this.exists || !this.parent.exists)
|
||||
{
|
||||
this.renderOrderID = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.autoCull)
|
||||
{
|
||||
// Won't get rendered but will still get its transform updated
|
||||
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
|
||||
}
|
||||
|
||||
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
|
||||
|
||||
if (this.visible)
|
||||
{
|
||||
this._cache[3] = this.game.stage.currentRenderOrderID++;
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Override and use this function in your own custom objects to handle any update requirements you may have.
|
||||
*
|
||||
* @method Phaser.Graphics#update
|
||||
* @memberof Phaser.Graphics
|
||||
*/
|
||||
Phaser.Graphics.prototype.update = function() {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Automatically called by World.postUpdate.
|
||||
* @method Phaser.Graphics.prototype.postUpdate
|
||||
*/
|
||||
Phaser.Graphics.prototype.postUpdate = function () {
|
||||
|
||||
// Fixed to Camera?
|
||||
if (this._cache[7] === 1)
|
||||
{
|
||||
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
|
||||
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroy this Graphics instance.
|
||||
*
|
||||
* @method Phaser.Graphics.prototype.destroy
|
||||
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
|
||||
*/
|
||||
Phaser.Graphics.prototype.destroy = function(destroyChildren) {
|
||||
|
||||
if (this.game === null || this.destroyPhase) { return; }
|
||||
|
||||
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
|
||||
|
||||
this._cache[8] = 1;
|
||||
|
||||
this.clear();
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
if (this.parent instanceof Phaser.Group)
|
||||
{
|
||||
this.parent.remove(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.parent.removeChild(this);
|
||||
}
|
||||
}
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
if (destroyChildren)
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].destroy(destroyChildren);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
this.game = null;
|
||||
|
||||
this._cache[8] = 0;
|
||||
|
||||
};
|
||||
|
||||
/*
|
||||
* Draws a {Phaser.Polygon} or a {PIXI.Polygon} filled
|
||||
*
|
||||
* @method Phaser.Graphics.prototype.drawPolygon
|
||||
*/
|
||||
Phaser.Graphics.prototype.drawPolygon = function (poly) {
|
||||
|
||||
this.moveTo(poly.points[0].x, poly.points[0].y);
|
||||
|
||||
for (var i = 1; i < poly.points.length; i += 1)
|
||||
{
|
||||
this.lineTo(poly.points[i].x, poly.points[i].y);
|
||||
}
|
||||
|
||||
this.lineTo(poly.points[0].x, poly.points[0].y);
|
||||
|
||||
};
|
||||
|
||||
/*
|
||||
* Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
|
||||
*
|
||||
* @method Phaser.Graphics.prototype.drawTriangle
|
||||
* @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
|
||||
* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
|
||||
*/
|
||||
Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
|
||||
|
||||
if (typeof cull === 'undefined') { cull = false; }
|
||||
|
||||
var triangle = new Phaser.Polygon(points);
|
||||
|
||||
if (cull)
|
||||
{
|
||||
var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
|
||||
var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
|
||||
var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
|
||||
var faceNormal = cb.cross(ab);
|
||||
|
||||
if (cameraToFace.dot(faceNormal) > 0)
|
||||
{
|
||||
this.drawPolygon(triangle);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.drawPolygon(triangle);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/*
|
||||
* Draws {Phaser.Polygon} triangles
|
||||
*
|
||||
* @method Phaser.Graphics.prototype.drawTriangles
|
||||
* @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
|
||||
* @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
|
||||
* @param {boolean} [cull=false] - Should we check if the triangle is back-facing
|
||||
*/
|
||||
Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
|
||||
|
||||
if (typeof cull === 'undefined') { cull = false; }
|
||||
|
||||
var point1 = new Phaser.Point();
|
||||
var point2 = new Phaser.Point();
|
||||
var point3 = new Phaser.Point();
|
||||
var points = [];
|
||||
var i;
|
||||
|
||||
if (!indices)
|
||||
{
|
||||
if (vertices[0] instanceof Phaser.Point)
|
||||
{
|
||||
for (i = 0; i < vertices.length / 3; i++)
|
||||
{
|
||||
this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (i = 0; i < vertices.length / 6; i++)
|
||||
{
|
||||
point1.x = vertices[i * 6 + 0];
|
||||
point1.y = vertices[i * 6 + 1];
|
||||
point2.x = vertices[i * 6 + 2];
|
||||
point2.y = vertices[i * 6 + 3];
|
||||
point3.x = vertices[i * 6 + 4];
|
||||
point3.y = vertices[i * 6 + 5];
|
||||
this.drawTriangle([point1, point2, point3], cull);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (vertices[0] instanceof Phaser.Point)
|
||||
{
|
||||
for (i = 0; i < indices.length /3; i++)
|
||||
{
|
||||
points.push(vertices[indices[i * 3 ]]);
|
||||
points.push(vertices[indices[i * 3 + 1]]);
|
||||
points.push(vertices[indices[i * 3 + 2]]);
|
||||
|
||||
if (points.length === 3)
|
||||
{
|
||||
this.drawTriangle(points, cull);
|
||||
points = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (i = 0; i < indices.length; i++)
|
||||
{
|
||||
point1.x = vertices[indices[i] * 2];
|
||||
point1.y = vertices[indices[i] * 2 + 1];
|
||||
points.push(point1.copyTo({}));
|
||||
|
||||
if (points.length === 3)
|
||||
{
|
||||
this.drawTriangle(points, cull);
|
||||
points = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Indicates the rotation of the Graphics, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
|
||||
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
|
||||
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
|
||||
*
|
||||
* @name Phaser.Graphics#angle
|
||||
* @property {number} angle - Gets or sets the angle of rotation in degrees.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Graphics.prototype, 'angle', {
|
||||
|
||||
get: function() {
|
||||
return Phaser.Math.radToDeg(this.rotation);
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
this.rotation = Phaser.Math.degToRad(value);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* An Graphics that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Graphics.cameraOffset.
|
||||
* Note that the cameraOffset values are in addition to any parent in the display list.
|
||||
* So if this Graphics was in a Group that has x: 200, then this will be added to the cameraOffset.x
|
||||
*
|
||||
* @name Phaser.Graphics#fixedToCamera
|
||||
* @property {boolean} fixedToCamera - Set to true to fix this Graphics to the Camera at its current world coordinates.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Graphics.prototype, "fixedToCamera", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[7];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
this._cache[7] = 1;
|
||||
this.cameraOffset.set(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._cache[7] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Graphics#destroyPhase
|
||||
* @property {boolean} destroyPhase - True if this object is currently being destroyed.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Graphics.prototype, "destroyPhase", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[8];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
792
src/gameobjects/Image.js
Normal file
792
src/gameobjects/Image.js
Normal file
@@ -0,0 +1,792 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Image
|
||||
*
|
||||
* @classdesc Create a new `Image` object. An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
|
||||
* It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
|
||||
*
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} x - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
|
||||
* @param {number} y - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
|
||||
* @param {string|number} frame - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
*/
|
||||
Phaser.Image = function (game, x, y, key, frame) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
key = key || null;
|
||||
frame = frame || null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - If exists = false then the Image isn't updated by the core game loop.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this Image.
|
||||
* @default
|
||||
*/
|
||||
this.name = '';
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @readonly
|
||||
*/
|
||||
this.type = Phaser.IMAGE;
|
||||
|
||||
/**
|
||||
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
|
||||
*/
|
||||
this.z = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Image or its components.
|
||||
*/
|
||||
this.events = new Phaser.Events(this);
|
||||
|
||||
/**
|
||||
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
|
||||
*/
|
||||
this.key = key;
|
||||
|
||||
/**
|
||||
* @property {number} _frame - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._frame = 0;
|
||||
|
||||
/**
|
||||
* @property {string} _frameName - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._frameName = '';
|
||||
|
||||
PIXI.Sprite.call(this, PIXI.TextureCache['__default']);
|
||||
|
||||
this.loadTexture(key, frame);
|
||||
|
||||
this.position.set(x, y);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} world - The world coordinates of this Image. This differs from the x/y coordinates which are relative to the Images container.
|
||||
*/
|
||||
this.world = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* Should this Image be automatically culled if out of range of the camera?
|
||||
* A culled sprite has its renderable property set to 'false'.
|
||||
* Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
|
||||
*
|
||||
* @property {boolean} autoCull - A flag indicating if the Image should be automatically camera culled or not.
|
||||
* @default
|
||||
*/
|
||||
this.autoCull = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
|
||||
*/
|
||||
this.cameraOffset = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* A small internal cache:
|
||||
* 0 = previous position.x
|
||||
* 1 = previous position.y
|
||||
* 2 = previous rotation
|
||||
* 3 = renderID
|
||||
* 4 = fresh? (0 = no, 1 = yes)
|
||||
* 5 = outOfBoundsFired (0 = no, 1 = yes)
|
||||
* 6 = exists (0 = no, 1 = yes)
|
||||
* 7 = fixed to camera (0 = no, 1 = yes)
|
||||
* 8 = destroy phase? (0 = no, 1 = yes)
|
||||
* @property {Array} _cache
|
||||
* @private
|
||||
*/
|
||||
this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
|
||||
|
||||
};
|
||||
|
||||
Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
|
||||
Phaser.Image.prototype.constructor = Phaser.Image;
|
||||
|
||||
/**
|
||||
* Automatically called by World.preUpdate.
|
||||
*
|
||||
* @method Phaser.Image#preUpdate
|
||||
* @memberof Phaser.Image
|
||||
*/
|
||||
Phaser.Image.prototype.preUpdate = function() {
|
||||
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (!this.exists || !this.parent.exists)
|
||||
{
|
||||
this._cache[3] = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.autoCull)
|
||||
{
|
||||
// Won't get rendered but will still get its transform updated
|
||||
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
|
||||
}
|
||||
|
||||
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
|
||||
|
||||
if (this.visible)
|
||||
{
|
||||
this._cache[3] = this.game.stage.currentRenderOrderID++;
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].preUpdate();
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Override and use this function in your own custom objects to handle any update requirements you may have.
|
||||
*
|
||||
* @method Phaser.Image#update
|
||||
* @memberof Phaser.Image
|
||||
*/
|
||||
Phaser.Image.prototype.update = function() {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function called by the World postUpdate cycle.
|
||||
*
|
||||
* @method Phaser.Image#postUpdate
|
||||
* @memberof Phaser.Image
|
||||
*/
|
||||
Phaser.Image.prototype.postUpdate = function() {
|
||||
|
||||
if (this.key instanceof Phaser.BitmapData)
|
||||
{
|
||||
this.key.render();
|
||||
}
|
||||
|
||||
// Fixed to Camera?
|
||||
if (this._cache[7] === 1)
|
||||
{
|
||||
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
|
||||
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].postUpdate();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes the Texture the Image is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
|
||||
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
|
||||
*
|
||||
* @method Phaser.Image#loadTexture
|
||||
* @memberof Phaser.Image
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
|
||||
* @param {string|number} frame - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
*/
|
||||
Phaser.Image.prototype.loadTexture = function (key, frame) {
|
||||
|
||||
frame = frame || 0;
|
||||
|
||||
if (key instanceof Phaser.RenderTexture)
|
||||
{
|
||||
this.key = key.key;
|
||||
this.setTexture(key);
|
||||
return;
|
||||
}
|
||||
else if (key instanceof Phaser.BitmapData)
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(key.texture);
|
||||
return;
|
||||
}
|
||||
else if (key instanceof PIXI.Texture)
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(key);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (key === null || typeof key === 'undefined')
|
||||
{
|
||||
this.key = '__default';
|
||||
this.setTexture(PIXI.TextureCache[this.key]);
|
||||
return;
|
||||
}
|
||||
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
|
||||
{
|
||||
this.key = '__missing';
|
||||
this.setTexture(PIXI.TextureCache[this.key]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.game.cache.isSpriteSheet(key))
|
||||
{
|
||||
this.key = key;
|
||||
|
||||
var frameData = this.game.cache.getFrameData(key);
|
||||
|
||||
if (typeof frame === 'string')
|
||||
{
|
||||
this._frame = 0;
|
||||
this._frameName = frame;
|
||||
this.setTexture(PIXI.TextureCache[frameData.getFrameByName(frame).uuid]);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
this._frame = frame;
|
||||
this._frameName = '';
|
||||
this.setTexture(PIXI.TextureCache[frameData.getFrame(frame).uuid]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(PIXI.TextureCache[key]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Crop allows you to crop the texture used to display this Image.
|
||||
* Cropping takes place from the top-left of the Image and can be modified in real-time by providing an updated rectangle object.
|
||||
* The rectangle object given to this method can be either a Phaser.Rectangle or any object so long as it has public x, y, width and height properties.
|
||||
* Please note that the rectangle object given is not duplicated by this method, but rather the Image uses a reference to the rectangle.
|
||||
* Keep this in mind if assigning a rectangle in a for-loop, or when cleaning up for garbage collection.
|
||||
*
|
||||
* @method Phaser.Image#crop
|
||||
* @memberof Phaser.Image
|
||||
* @param {Phaser.Rectangle|object} rect - The Rectangle to crop the Image to. Pass null or no parameters to clear a previously set crop rectangle.
|
||||
*/
|
||||
Phaser.Image.prototype.crop = function(rect) {
|
||||
|
||||
if (typeof rect === 'undefined' || rect === null)
|
||||
{
|
||||
// Clear any crop that may be set
|
||||
if (this.texture.hasOwnProperty('sourceWidth'))
|
||||
{
|
||||
this.texture.setFrame(new Phaser.Rectangle(0, 0, this.texture.sourceWidth, this.texture.sourceHeight));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Do we need to clone the PIXI.Texture object?
|
||||
if (this.texture instanceof PIXI.Texture)
|
||||
{
|
||||
// Yup, let's rock it ...
|
||||
var local = {};
|
||||
|
||||
Phaser.Utils.extend(true, local, this.texture);
|
||||
|
||||
local.sourceWidth = local.width;
|
||||
local.sourceHeight = local.height;
|
||||
local.frame = rect;
|
||||
local.width = rect.width;
|
||||
local.height = rect.height;
|
||||
|
||||
this.texture = local;
|
||||
|
||||
this.texture.updateFrame = true;
|
||||
PIXI.Texture.frameUpdates.push(this.texture);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.texture.setFrame(rect);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Brings a 'dead' Image back to life, optionally giving it the health value specified.
|
||||
* A resurrected Image has its alive, exists and visible properties all set to true.
|
||||
* It will dispatch the onRevived event, you can listen to Image.events.onRevived for the signal.
|
||||
*
|
||||
* @method Phaser.Image#revive
|
||||
* @memberof Phaser.Image
|
||||
* @return {Phaser.Image} This instance.
|
||||
*/
|
||||
Phaser.Image.prototype.revive = function() {
|
||||
|
||||
this.alive = true;
|
||||
this.exists = true;
|
||||
this.visible = true;
|
||||
|
||||
if (this.events)
|
||||
{
|
||||
this.events.onRevived.dispatch(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Kills a Image. A killed Image has its alive, exists and visible properties all set to false.
|
||||
* It will dispatch the onKilled event, you can listen to Image.events.onKilled for the signal.
|
||||
* Note that killing a Image is a way for you to quickly recycle it in a Image pool, it doesn't free it up from memory.
|
||||
* If you don't need this Image any more you should call Image.destroy instead.
|
||||
*
|
||||
* @method Phaser.Image#kill
|
||||
* @memberof Phaser.Image
|
||||
* @return {Phaser.Image} This instance.
|
||||
*/
|
||||
Phaser.Image.prototype.kill = function() {
|
||||
|
||||
this.alive = false;
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
if (this.events)
|
||||
{
|
||||
this.events.onKilled.dispatch(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroys the Image. This removes it from its parent group, destroys the input, event and animation handlers if present
|
||||
* and nulls its reference to game, freeing it up for garbage collection.
|
||||
*
|
||||
* @method Phaser.Image#destroy
|
||||
* @memberof Phaser.Image
|
||||
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
|
||||
*/
|
||||
Phaser.Image.prototype.destroy = function(destroyChildren) {
|
||||
|
||||
if (this.game === null || this.destroyPhase) { return; }
|
||||
|
||||
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
|
||||
|
||||
this._cache[8] = 1;
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
if (this.parent instanceof Phaser.Group)
|
||||
{
|
||||
this.parent.remove(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.parent.removeChild(this);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.events)
|
||||
{
|
||||
this.events.destroy();
|
||||
}
|
||||
|
||||
if (this.input)
|
||||
{
|
||||
this.input.destroy();
|
||||
}
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
if (destroyChildren)
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].destroy(destroyChildren);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
this.alive = false;
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
this.filters = null;
|
||||
this.mask = null;
|
||||
this.game = null;
|
||||
|
||||
this._cache[8] = 0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets the Image. This places the Image at the given x/y world coordinates and then sets alive, exists, visible and renderable all to true.
|
||||
*
|
||||
* @method Phaser.Image#reset
|
||||
* @memberof Phaser.Image
|
||||
* @param {number} x - The x coordinate (in world space) to position the Image at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the Image at.
|
||||
* @return {Phaser.Image} This instance.
|
||||
*/
|
||||
Phaser.Image.prototype.reset = function(x, y) {
|
||||
|
||||
this.world.setTo(x, y);
|
||||
this.position.x = x;
|
||||
this.position.y = y;
|
||||
this.alive = true;
|
||||
this.exists = true;
|
||||
this.visible = true;
|
||||
this.renderable = true;
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Brings the Image to the top of the display list it is a child of. Images that are members of a Phaser.Group are only
|
||||
* bought to the top of that Group, not the entire display list.
|
||||
*
|
||||
* @method Phaser.Image#bringToTop
|
||||
* @memberof Phaser.Image
|
||||
* @return {Phaser.Image} This instance.
|
||||
*/
|
||||
Phaser.Image.prototype.bringToTop = function() {
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
this.parent.bringToTop(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Indicates the rotation of the Image, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
|
||||
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
|
||||
* If you wish to work in radians instead of degrees use the property Image.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
|
||||
*
|
||||
* @name Phaser.Image#angle
|
||||
* @property {number} angle - The angle of this Image in degrees.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "angle", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
|
||||
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the delta x value. The difference between world.x now and in the previous step.
|
||||
*
|
||||
* @name Phaser.Image#deltaX
|
||||
* @property {number} deltaX - The delta value. Positive if the motion was to the right, negative if to the left.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "deltaX", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this.world.x - this._cache[0];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the delta y value. The difference between world.y now and in the previous step.
|
||||
*
|
||||
* @name Phaser.Image#deltaY
|
||||
* @property {number} deltaY - The delta value. Positive if the motion was downwards, negative if upwards.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "deltaY", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this.world.y - this._cache[1];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the delta z value. The difference between rotation now and in the previous step.
|
||||
*
|
||||
* @name Phaser.Image#deltaZ
|
||||
* @property {number} deltaZ - The delta value.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "deltaZ", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this.rotation - this._cache[2];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Checks if the Image bounds are within the game world, otherwise false if fully outside of it.
|
||||
*
|
||||
* @name Phaser.Image#inWorld
|
||||
* @property {boolean} inWorld - True if the Image bounds is within the game world, even if only partially. Otherwise false if fully outside of it.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "inWorld", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this.game.world.bounds.intersects(this.getBounds());
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Checks if the Image bounds are within the game camera, otherwise false if fully outside of it.
|
||||
*
|
||||
* @name Phaser.Image#inCamera
|
||||
* @property {boolean} inCamera - True if the Image bounds is within the game camera, even if only partially. Otherwise false if fully outside of it.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "inCamera", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this.game.world.camera.screenView.intersects(this.getBounds());
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Image#frame
|
||||
* @property {number} frame - Gets or sets the current frame index and updates the Texture for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "frame", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this._frame;
|
||||
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.frame && this.game.cache.isSpriteSheet(this.key))
|
||||
{
|
||||
var frameData = this.game.cache.getFrameData(this.key);
|
||||
|
||||
if (frameData && value < frameData.total && frameData.getFrame(value))
|
||||
{
|
||||
this.setTexture(PIXI.TextureCache[frameData.getFrame(value).uuid]);
|
||||
this._frame = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Image#frameName
|
||||
* @property {string} frameName - Gets or sets the current frame by name and updates the Texture for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "frameName", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this._frameName;
|
||||
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.frameName && this.game.cache.isSpriteSheet(this.key))
|
||||
{
|
||||
var frameData = this.game.cache.getFrameData(this.key);
|
||||
|
||||
if (frameData && frameData.getFrameByName(value))
|
||||
{
|
||||
this.setTexture(PIXI.TextureCache[frameData.getFrameByName(value).uuid]);
|
||||
this._frameName = value;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Image#renderOrderID
|
||||
* @property {number} renderOrderID - The render order ID, reset every frame.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "renderOrderID", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return this._cache[3];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* By default an Image won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
|
||||
* activated for this object and it will then start to process click/touch events and more.
|
||||
*
|
||||
* @name Phaser.Image#inputEnabled
|
||||
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "inputEnabled", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return (this.input && this.input.enabled);
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (this.input === null)
|
||||
{
|
||||
this.input = new Phaser.InputHandler(this);
|
||||
this.input.start();
|
||||
}
|
||||
else if (this.input && !this.input.enabled)
|
||||
{
|
||||
this.input.start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.input && this.input.enabled)
|
||||
{
|
||||
this.input.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* An Image that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Image.cameraOffset.
|
||||
* Note that the cameraOffset values are in addition to any parent in the display list.
|
||||
* So if this Image was in a Group that has x: 200, then this will be added to the cameraOffset.x
|
||||
*
|
||||
* @name Phaser.Image#fixedToCamera
|
||||
* @property {boolean} fixedToCamera - Set to true to fix this Image to the Camera at its current world coordinates.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "fixedToCamera", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[7];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
this._cache[7] = 1;
|
||||
this.cameraOffset.set(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._cache[7] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Enable or disable texture smoothing for this Image. Only works for bitmap/image textures. Smoothing is enabled by default.
|
||||
*
|
||||
* @name Phaser.Image#smoothed
|
||||
* @property {boolean} smoothed - Set to true to smooth the texture of this Image, or false to disable smoothing (great for pixel art)
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "smoothed", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !this.texture.baseTexture.scaleMode;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (this.texture)
|
||||
{
|
||||
this.texture.baseTexture.scaleMode = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.texture)
|
||||
{
|
||||
this.texture.baseTexture.scaleMode = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Image#destroyPhase
|
||||
* @property {boolean} destroyPhase - True if this object is currently being destroyed.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Image.prototype, "destroyPhase", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[8];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
184
src/gameobjects/Particle.js
Normal file
184
src/gameobjects/Particle.js
Normal file
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Particle
|
||||
*
|
||||
* @classdesc Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter.
|
||||
*
|
||||
* @constructor
|
||||
* @extends Phaser.Sprite
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} x - The x coordinate (in world space) to position the Particle at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the Particle at.
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
*/
|
||||
Phaser.Particle = function (game, x, y, key, frame) {
|
||||
|
||||
Phaser.Sprite.call(this, game, x, y, key, frame);
|
||||
|
||||
/**
|
||||
* @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData.
|
||||
* @protected
|
||||
*/
|
||||
this.autoScale = false;
|
||||
|
||||
/**
|
||||
* @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle.
|
||||
* @protected
|
||||
*/
|
||||
this.scaleData = null;
|
||||
|
||||
/**
|
||||
* @property {number} _s - Internal cache var for tracking auto scale.
|
||||
* @private
|
||||
*/
|
||||
this._s = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData.
|
||||
* @protected
|
||||
*/
|
||||
this.autoAlpha = false;
|
||||
|
||||
/**
|
||||
* @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle.
|
||||
* @protected
|
||||
*/
|
||||
this.alphaData = null;
|
||||
|
||||
/**
|
||||
* @property {number} _a - Internal cache var for tracking auto alpha.
|
||||
* @private
|
||||
*/
|
||||
this._a = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype);
|
||||
Phaser.Particle.prototype.constructor = Phaser.Particle;
|
||||
|
||||
/**
|
||||
* Updates the Particle scale or alpha if autoScale and autoAlpha are set.
|
||||
*
|
||||
* @method Phaser.Particle#update
|
||||
* @memberof Phaser.Particle
|
||||
*/
|
||||
Phaser.Particle.prototype.update = function() {
|
||||
|
||||
if (this.autoScale)
|
||||
{
|
||||
this._s--;
|
||||
|
||||
if (this._s)
|
||||
{
|
||||
this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.autoScale = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.autoAlpha)
|
||||
{
|
||||
this._a--;
|
||||
|
||||
if (this._a)
|
||||
{
|
||||
this.alpha = this.alphaData[this._a].v;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.autoAlpha = false;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required.
|
||||
*
|
||||
* @method Phaser.Particle#onEmit
|
||||
* @memberof Phaser.Particle
|
||||
*/
|
||||
Phaser.Particle.prototype.onEmit = function() {
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter.
|
||||
*
|
||||
* @method Phaser.Particle#setAlphaData
|
||||
* @memberof Phaser.Particle
|
||||
*/
|
||||
Phaser.Particle.prototype.setAlphaData = function(data) {
|
||||
|
||||
this.alphaData = data;
|
||||
this._a = data.length - 1;
|
||||
this.alpha = this.alphaData[this._a].v;
|
||||
this.autoAlpha = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter.
|
||||
*
|
||||
* @method Phaser.Particle#setScaleData
|
||||
* @memberof Phaser.Particle
|
||||
*/
|
||||
Phaser.Particle.prototype.setScaleData = function(data) {
|
||||
|
||||
this.scaleData = data;
|
||||
this._s = data.length - 1;
|
||||
this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
|
||||
this.autoScale = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets the Particle. This places the Particle at the given x/y world coordinates and then
|
||||
* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
|
||||
* If the Particle has a physics body that too is reset.
|
||||
*
|
||||
* @method Phaser.Particle#reset
|
||||
* @memberof Phaser.Particle
|
||||
* @param {number} x - The x coordinate (in world space) to position the Particle at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the Particle at.
|
||||
* @param {number} [health=1] - The health to give the Particle.
|
||||
* @return (Phaser.Particle) This instance.
|
||||
*/
|
||||
Phaser.Particle.prototype.reset = function(x, y, health) {
|
||||
|
||||
if (typeof health === 'undefined') { health = 1; }
|
||||
|
||||
this.world.setTo(x, y);
|
||||
this.position.x = x;
|
||||
this.position.y = y;
|
||||
this.alive = true;
|
||||
this.exists = true;
|
||||
this.visible = true;
|
||||
this.renderable = true;
|
||||
this._outOfBoundsFired = false;
|
||||
|
||||
this.health = health;
|
||||
|
||||
if (this.body)
|
||||
{
|
||||
this.body.reset(x, y, false, false);
|
||||
}
|
||||
|
||||
this._cache[4] = 1;
|
||||
|
||||
this.alpha = 1;
|
||||
this.scale.set(1);
|
||||
|
||||
this.autoScale = false;
|
||||
this.autoAlpha = false;
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
85
src/gameobjects/RenderTexture.js
Normal file
85
src/gameobjects/RenderTexture.js
Normal file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A RenderTexture is a special texture that allows any displayObject to be rendered to it.
|
||||
* @class Phaser.RenderTexture
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {string} key - Internal Phaser reference key for the render texture.
|
||||
* @param {number} [width=100] - The width of the render texture.
|
||||
* @param {number} [height=100] - The height of the render texture.
|
||||
* @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there.
|
||||
* @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts.
|
||||
*/
|
||||
Phaser.RenderTexture = function (game, width, height, key, scaleMode) {
|
||||
|
||||
if (typeof key === 'undefined') { key = ''; }
|
||||
if (typeof scaleMode === 'undefined') { scaleMode = Phaser.scaleModes.DEFAULT; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {string} key - The key of the RenderTexture in the Cache, if stored there.
|
||||
*/
|
||||
this.key = key;
|
||||
|
||||
/**
|
||||
* @property {number} type - Base Phaser object type.
|
||||
*/
|
||||
this.type = Phaser.RENDERTEXTURE;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} _temp - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this._temp = new Phaser.Point();
|
||||
|
||||
PIXI.RenderTexture.call(this, width, height, scaleMode);
|
||||
|
||||
};
|
||||
|
||||
Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
|
||||
Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
|
||||
|
||||
/**
|
||||
* This function will draw the display object to the texture.
|
||||
*
|
||||
* @method Phaser.RenderTexture.prototype.renderXY
|
||||
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
|
||||
* @param {number} x - The x position to render the object at.
|
||||
* @param {number} y - The y position to render the object at.
|
||||
* @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
|
||||
*/
|
||||
Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
|
||||
|
||||
this._temp.set(x, y);
|
||||
|
||||
this.render(displayObject, this._temp, clear);
|
||||
|
||||
};
|
||||
|
||||
// Documentation stubs
|
||||
|
||||
/**
|
||||
* This function will draw the display object to the texture.
|
||||
*
|
||||
* @method Phaser.RenderTexture.prototype.render
|
||||
* @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject The display object to render to this texture.
|
||||
* @param {Phaser.Point} position - A Point object containing the position to render the display object at.
|
||||
* @param {boolean} clear - If true the texture will be cleared before the display object is drawn.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resize this RenderTexture to the given width and height.
|
||||
*
|
||||
* @method Phaser.RenderTexture.prototype.resize
|
||||
* @param {number} width - The new width of the RenderTexture.
|
||||
* @param {number} height - The new height of the RenderTexture.
|
||||
*/
|
||||
537
src/gameobjects/RetroFont.js
Normal file
537
src/gameobjects/RetroFont.js
Normal file
@@ -0,0 +1,537 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.RetroFont
|
||||
* @extends Phaser.RenderTexture
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {string} key - The font set graphic set as stored in the Game.Cache.
|
||||
* @param {number} characterWidth - The width of each character in the font set.
|
||||
* @param {number} characterHeight - The height of each character in the font set.
|
||||
* @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
|
||||
* @param {number} charsPerRow - The number of characters per row in the font set.
|
||||
* @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
|
||||
* @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
|
||||
* @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
|
||||
* @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
|
||||
*/
|
||||
Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
|
||||
|
||||
/**
|
||||
* @property {number} characterWidth - The width of each character in the font set.
|
||||
*/
|
||||
this.characterWidth = characterWidth;
|
||||
|
||||
/**
|
||||
* @property {number} characterHeight - The height of each character in the font set.
|
||||
*/
|
||||
this.characterHeight = characterHeight;
|
||||
|
||||
/**
|
||||
* @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
|
||||
*/
|
||||
this.characterSpacingX = xSpacing || 0;
|
||||
|
||||
/**
|
||||
* @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
|
||||
*/
|
||||
this.characterSpacingY = ySpacing || 0;
|
||||
|
||||
/**
|
||||
* @property {number} characterPerRow - The number of characters per row in the font set.
|
||||
*/
|
||||
this.characterPerRow = charsPerRow;
|
||||
|
||||
/**
|
||||
* @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
|
||||
*/
|
||||
this.offsetX = xOffset || 0;
|
||||
|
||||
/**
|
||||
* @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
|
||||
*/
|
||||
this.offsetY = yOffset || 0;
|
||||
|
||||
/**
|
||||
* @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
|
||||
*/
|
||||
this.align = "left";
|
||||
|
||||
/**
|
||||
* @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default)
|
||||
* @default
|
||||
*/
|
||||
this.multiLine = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true.
|
||||
* @default
|
||||
*/
|
||||
this.autoUpperCase = true;
|
||||
|
||||
/**
|
||||
* @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
|
||||
* @default
|
||||
*/
|
||||
this.customSpacingX = 0;
|
||||
|
||||
/**
|
||||
* @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
|
||||
* @default
|
||||
*/
|
||||
this.customSpacingY = 0;
|
||||
|
||||
/**
|
||||
* If you need this RetroFont image to have a fixed width you can set the width in this value.
|
||||
* If text is wider than the width specified it will be cropped off.
|
||||
* @property {number} fixedWidth
|
||||
*/
|
||||
this.fixedWidth = 0;
|
||||
|
||||
/**
|
||||
* @property {HTMLImage} fontSet - A reference to the image stored in the Game.Cache that contains the font.
|
||||
*/
|
||||
this.fontSet = game.cache.getImage(key);
|
||||
|
||||
/**
|
||||
* @property {string} _text - The text of the font image.
|
||||
* @private
|
||||
*/
|
||||
this._text = '';
|
||||
|
||||
/**
|
||||
* @property {array} grabData - An array of rects for faster character pasting.
|
||||
* @private
|
||||
*/
|
||||
this.grabData = [];
|
||||
|
||||
// Now generate our rects for faster copying later on
|
||||
var currentX = this.offsetX;
|
||||
var currentY = this.offsetY;
|
||||
var r = 0;
|
||||
var data = new Phaser.FrameData();
|
||||
|
||||
for (var c = 0; c < chars.length; c++)
|
||||
{
|
||||
var uuid = game.rnd.uuid();
|
||||
|
||||
var frame = data.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight, '', uuid));
|
||||
|
||||
this.grabData[chars.charCodeAt(c)] = frame.index;
|
||||
|
||||
PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], {
|
||||
x: currentX,
|
||||
y: currentY,
|
||||
width: this.characterWidth,
|
||||
height: this.characterHeight
|
||||
});
|
||||
|
||||
r++;
|
||||
|
||||
if (r == this.characterPerRow)
|
||||
{
|
||||
r = 0;
|
||||
currentX = this.offsetX;
|
||||
currentY += this.characterHeight + this.characterSpacingY;
|
||||
}
|
||||
else
|
||||
{
|
||||
currentX += this.characterWidth + this.characterSpacingX;
|
||||
}
|
||||
}
|
||||
|
||||
game.cache.updateFrameData(key, data);
|
||||
|
||||
this.stamp = new Phaser.Image(game, 0, 0, key, 0);
|
||||
|
||||
Phaser.RenderTexture.call(this, game);
|
||||
|
||||
/**
|
||||
* @property {number} type - Base Phaser object type.
|
||||
*/
|
||||
this.type = Phaser.RETROFONT;
|
||||
|
||||
};
|
||||
|
||||
Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
|
||||
Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
|
||||
|
||||
/**
|
||||
* Align each line of multi-line text to the left.
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.ALIGN_LEFT = "left";
|
||||
|
||||
/**
|
||||
* Align each line of multi-line text to the right.
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.ALIGN_RIGHT = "right";
|
||||
|
||||
/**
|
||||
* Align each line of multi-line text in the center.
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.ALIGN_CENTER = "center";
|
||||
|
||||
/**
|
||||
* Text Set 1 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
|
||||
|
||||
/**
|
||||
* Text Set 2 = !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
/**
|
||||
* Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
|
||||
|
||||
/**
|
||||
* Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
|
||||
|
||||
/**
|
||||
* Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
|
||||
|
||||
/**
|
||||
* Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.'
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
|
||||
|
||||
/**
|
||||
* Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
|
||||
|
||||
/**
|
||||
* Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
/**
|
||||
* Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
|
||||
|
||||
/**
|
||||
* Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
/**
|
||||
* Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789
|
||||
* @constant
|
||||
* @type {string}
|
||||
*/
|
||||
Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
|
||||
|
||||
/**
|
||||
* If you need this FlxSprite to have a fixed width and custom alignment you can set the width here.<br>
|
||||
* If text is wider than the width specified it will be cropped off.
|
||||
*
|
||||
* @method Phaser.RetroFont#setFixedWidth
|
||||
* @memberof Phaser.RetroFont
|
||||
* @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
|
||||
* @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
|
||||
*/
|
||||
Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
|
||||
|
||||
if (typeof lineAlignment === 'undefined') { lineAlignment = 'left'; }
|
||||
|
||||
this.fixedWidth = width;
|
||||
this.align = lineAlignment;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A helper function that quickly sets lots of variables at once, and then updates the text.
|
||||
*
|
||||
* @method Phaser.RetroFont#setText
|
||||
* @memberof Phaser.RetroFont
|
||||
* @param {string} content - The text of this sprite.
|
||||
* @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line.
|
||||
* @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
|
||||
* @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
|
||||
* @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
|
||||
* @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true.
|
||||
*/
|
||||
Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
|
||||
|
||||
this.multiLine = multiLine || false;
|
||||
this.customSpacingX = characterSpacing || 0;
|
||||
this.customSpacingY = lineSpacing || 0;
|
||||
this.align = lineAlignment || 'left';
|
||||
|
||||
if (allowLowerCase)
|
||||
{
|
||||
this.autoUpperCase = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.autoUpperCase = true;
|
||||
}
|
||||
|
||||
if (content.length > 0)
|
||||
{
|
||||
this.text = content;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the BitmapData of the Sprite with the text
|
||||
*
|
||||
* @method Phaser.RetroFont#buildRetroFontText
|
||||
* @memberof Phaser.RetroFont
|
||||
*/
|
||||
Phaser.RetroFont.prototype.buildRetroFontText = function () {
|
||||
|
||||
var cx = 0;
|
||||
var cy = 0;
|
||||
|
||||
this.clear();
|
||||
|
||||
if (this.multiLine)
|
||||
{
|
||||
var lines = this._text.split("\n");
|
||||
|
||||
if (this.fixedWidth > 0)
|
||||
{
|
||||
this.resize(this.fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
|
||||
}
|
||||
|
||||
// Loop through each line of text
|
||||
for (var i = 0; i < lines.length; i++)
|
||||
{
|
||||
// This line of text is held in lines[i] - need to work out the alignment
|
||||
switch (this.align)
|
||||
{
|
||||
case Phaser.RetroFont.ALIGN_LEFT:
|
||||
cx = 0;
|
||||
break;
|
||||
|
||||
case Phaser.RetroFont.ALIGN_RIGHT:
|
||||
cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
|
||||
break;
|
||||
|
||||
case Phaser.RetroFont.ALIGN_CENTER:
|
||||
cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
|
||||
cx += this.customSpacingX / 2;
|
||||
break;
|
||||
}
|
||||
|
||||
// Sanity checks
|
||||
if (cx < 0)
|
||||
{
|
||||
cx = 0;
|
||||
}
|
||||
|
||||
this.pasteLine(lines[i], cx, cy, this.customSpacingX);
|
||||
|
||||
cy += this.characterHeight + this.customSpacingY;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.fixedWidth > 0)
|
||||
{
|
||||
this.resize(this.fixedWidth, this.characterHeight, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true);
|
||||
}
|
||||
|
||||
switch (this.align)
|
||||
{
|
||||
case Phaser.RetroFont.ALIGN_LEFT:
|
||||
cx = 0;
|
||||
break;
|
||||
|
||||
case Phaser.RetroFont.ALIGN_RIGHT:
|
||||
cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
|
||||
break;
|
||||
|
||||
case Phaser.RetroFont.ALIGN_CENTER:
|
||||
cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
|
||||
cx += this.customSpacingX / 2;
|
||||
break;
|
||||
}
|
||||
|
||||
this.textureBuffer.clear();
|
||||
|
||||
this.pasteLine(this._text, cx, 0, this.customSpacingX);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
|
||||
* Used by getLine and getMultiLine
|
||||
*
|
||||
* @method Phaser.RetroFont#buildRetroFontText
|
||||
* @memberof Phaser.RetroFont
|
||||
* @param {string} line - The single line of text to paste.
|
||||
* @param {number} x - The x coordinate.
|
||||
* @param {number} y - The y coordinate.
|
||||
* @param {number} customSpacingX - Custom X spacing.
|
||||
*/
|
||||
Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
|
||||
|
||||
var p = new Phaser.Point();
|
||||
|
||||
for (var c = 0; c < line.length; c++)
|
||||
{
|
||||
// If it's a space then there is no point copying, so leave a blank space
|
||||
if (line.charAt(c) == " ")
|
||||
{
|
||||
x += this.characterWidth + customSpacingX;
|
||||
}
|
||||
else
|
||||
{
|
||||
// If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
|
||||
if (this.grabData[line.charCodeAt(c)] >= 0)
|
||||
{
|
||||
this.stamp.frame = this.grabData[line.charCodeAt(c)];
|
||||
p.set(x, y);
|
||||
this.render(this.stamp, p, false);
|
||||
|
||||
x += this.characterWidth + customSpacingX;
|
||||
|
||||
if (x > this.width)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Works out the longest line of text in _text and returns its length
|
||||
*
|
||||
* @method Phaser.RetroFont#getLongestLine
|
||||
* @memberof Phaser.RetroFont
|
||||
* @return {number} The length of the longest line of text.
|
||||
*/
|
||||
Phaser.RetroFont.prototype.getLongestLine = function () {
|
||||
|
||||
var longestLine = 0;
|
||||
|
||||
if (this._text.length > 0)
|
||||
{
|
||||
var lines = this._text.split("\n");
|
||||
|
||||
for (var i = 0; i < lines.length; i++)
|
||||
{
|
||||
if (lines[i].length > longestLine)
|
||||
{
|
||||
longestLine = lines[i].length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return longestLine;
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
|
||||
*
|
||||
* @method Phaser.RetroFont#removeUnsupportedCharacters
|
||||
* @memberof Phaser.RetroFont
|
||||
* @protected
|
||||
* @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
|
||||
* @return {string} A clean version of the string.
|
||||
*/
|
||||
Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
|
||||
|
||||
var newString = "";
|
||||
|
||||
for (var c = 0; c < this._text.length; c++)
|
||||
{
|
||||
var aChar = this._text[c];
|
||||
var code = aChar.charCodeAt(0);
|
||||
|
||||
if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n"))
|
||||
{
|
||||
newString = newString.concat(aChar);
|
||||
}
|
||||
}
|
||||
|
||||
return newString;
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.BitmapText#text
|
||||
* @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
|
||||
*/
|
||||
Object.defineProperty(Phaser.RetroFont.prototype, "text", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this._text;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
var newText;
|
||||
|
||||
if (this.autoUpperCase)
|
||||
{
|
||||
newText = value.toUpperCase();
|
||||
}
|
||||
else
|
||||
{
|
||||
newText = value;
|
||||
}
|
||||
|
||||
if (newText !== this._text)
|
||||
{
|
||||
this._text = newText;
|
||||
|
||||
this.removeUnsupportedCharacters(this.multiLine);
|
||||
|
||||
this.buildRetroFontText();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
1084
src/gameobjects/Sprite.js
Normal file
1084
src/gameobjects/Sprite.js
Normal file
File diff suppressed because it is too large
Load Diff
35
src/gameobjects/SpriteBatch.js
Normal file
35
src/gameobjects/SpriteBatch.js
Normal file
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser SpriteBatch constructor.
|
||||
*
|
||||
* @classdesc The SpriteBatch class is a really fast version of the DisplayObjectContainer built solely for speed, so use when you need a lot of sprites or particles.
|
||||
* @class Phaser.SpriteBatch
|
||||
* @extends Phaser.Group
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {Phaser.Group|Phaser.Sprite} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If undefined or null it will use game.world.
|
||||
* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
|
||||
* @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
|
||||
*/
|
||||
Phaser.SpriteBatch = function (game, parent, name, addToStage) {
|
||||
|
||||
PIXI.SpriteBatch.call(this);
|
||||
|
||||
Phaser.Group.call(this, game, parent, name, addToStage);
|
||||
|
||||
/**
|
||||
* @property {number} type - Internal Phaser Type value.
|
||||
* @protected
|
||||
*/
|
||||
this.type = Phaser.SPRITEBATCH;
|
||||
|
||||
};
|
||||
|
||||
Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, Phaser.Group.prototype, PIXI.SpriteBatch.prototype);
|
||||
|
||||
Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
|
||||
908
src/gameobjects/Text.js
Normal file
908
src/gameobjects/Text.js
Normal file
@@ -0,0 +1,908 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a new `Text` object. This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for renderning to the view.
|
||||
* Because of this you can only display fonts that are currently loaded and available to the browser. It won't load the fonts for you.
|
||||
* Here is a compatibility table showing the available default fonts across different mobile browsers: http://www.jordanm.co.uk/tinytype
|
||||
*
|
||||
* @class Phaser.Text
|
||||
* @extends PIXI.Text
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {number} x - X position of the new text object.
|
||||
* @param {number} y - Y position of the new text object.
|
||||
* @param {string} text - The actual text that will be written.
|
||||
* @param {object} style - The style object containing style attributes like font, font size ,
|
||||
*/
|
||||
Phaser.Text = function (game, x, y, text, style) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
text = text || ' ';
|
||||
style = style || {};
|
||||
|
||||
if (text.length === 0)
|
||||
{
|
||||
text = ' ';
|
||||
}
|
||||
else
|
||||
{
|
||||
text = text.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - If exists = false then the Text isn't updated by the core game loop.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this object.
|
||||
* @default
|
||||
*/
|
||||
this.name = '';
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @default
|
||||
*/
|
||||
this.type = Phaser.TEXT;
|
||||
|
||||
/**
|
||||
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
|
||||
*/
|
||||
this.z = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
|
||||
*/
|
||||
this.world = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* @property {string} _text - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._text = text;
|
||||
|
||||
/**
|
||||
* @property {string} _font - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._font = '';
|
||||
|
||||
/**
|
||||
* @property {number} _fontSize - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._fontSize = 32;
|
||||
|
||||
/**
|
||||
* @property {string} _fontWeight - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._fontWeight = 'normal';
|
||||
|
||||
/**
|
||||
* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
|
||||
* @private
|
||||
*/
|
||||
this._lineSpacing = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
|
||||
*/
|
||||
this.events = new Phaser.Events(this);
|
||||
|
||||
/**
|
||||
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
|
||||
*/
|
||||
this.cameraOffset = new Phaser.Point();
|
||||
|
||||
this.setStyle(style);
|
||||
|
||||
PIXI.Text.call(this, text, this.style);
|
||||
|
||||
this.position.set(x, y);
|
||||
|
||||
/**
|
||||
* A small internal cache:
|
||||
* 0 = previous position.x
|
||||
* 1 = previous position.y
|
||||
* 2 = previous rotation
|
||||
* 3 = renderID
|
||||
* 4 = fresh? (0 = no, 1 = yes)
|
||||
* 5 = outOfBoundsFired (0 = no, 1 = yes)
|
||||
* 6 = exists (0 = no, 1 = yes)
|
||||
* 7 = fixed to camera (0 = no, 1 = yes)
|
||||
* 8 = destroy phase? (0 = no, 1 = yes)
|
||||
* @property {Array} _cache
|
||||
* @private
|
||||
*/
|
||||
this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
|
||||
|
||||
};
|
||||
|
||||
Phaser.Text.prototype = Object.create(PIXI.Text.prototype);
|
||||
Phaser.Text.prototype.constructor = Phaser.Text;
|
||||
|
||||
/**
|
||||
* Automatically called by World.preUpdate.
|
||||
* @method Phaser.Text.prototype.preUpdate
|
||||
*/
|
||||
Phaser.Text.prototype.preUpdate = function () {
|
||||
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (!this.exists || !this.parent.exists)
|
||||
{
|
||||
this.renderOrderID = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.autoCull)
|
||||
{
|
||||
// Won't get rendered but will still get its transform updated
|
||||
this.renderable = this.game.world.camera.screenView.intersects(this.getBounds());
|
||||
}
|
||||
|
||||
this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]);
|
||||
|
||||
if (this.visible)
|
||||
{
|
||||
this._cache[3] = this.game.stage.currentRenderOrderID++;
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].preUpdate();
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Override and use this function in your own custom objects to handle any update requirements you may have.
|
||||
*
|
||||
* @method Phaser.Text#update
|
||||
* @memberof Phaser.Text
|
||||
*/
|
||||
Phaser.Text.prototype.update = function() {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Automatically called by World.postUpdate.
|
||||
* @method Phaser.Text.prototype.postUpdate
|
||||
*/
|
||||
Phaser.Text.prototype.postUpdate = function () {
|
||||
|
||||
if (this._cache[7] === 1)
|
||||
{
|
||||
this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
|
||||
this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].postUpdate();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @method Phaser.Text.prototype.destroy
|
||||
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
|
||||
*/
|
||||
Phaser.Text.prototype.destroy = function (destroyChildren) {
|
||||
|
||||
if (this.game === null || this.destroyPhase) { return; }
|
||||
|
||||
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
|
||||
|
||||
this._cache[8] = 1;
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
if (this.parent instanceof Phaser.Group)
|
||||
{
|
||||
this.parent.remove(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.parent.removeChild(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.texture.destroy();
|
||||
|
||||
if (this.canvas.parentNode)
|
||||
{
|
||||
this.canvas.parentNode.removeChild(this.canvas);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.canvas = null;
|
||||
this.context = null;
|
||||
}
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
if (destroyChildren)
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].destroy(destroyChildren);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
this.filters = null;
|
||||
this.mask = null;
|
||||
this.game = null;
|
||||
|
||||
this._cache[8] = 0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @method Phaser.Text.prototype.setShadow
|
||||
* @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
|
||||
* @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
|
||||
* @param {string} [color='rgba(0,0,0,0)'] - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
|
||||
* @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
|
||||
*/
|
||||
Phaser.Text.prototype.setShadow = function (x, y, color, blur) {
|
||||
|
||||
this.style.shadowOffsetX = x || 0;
|
||||
this.style.shadowOffsetY = y || 0;
|
||||
this.style.shadowColor = color || 'rgba(0,0,0,0)';
|
||||
this.style.shadowBlur = blur || 0;
|
||||
this.dirty = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Set the style of the text by passing a single style object to it.
|
||||
*
|
||||
* @method Phaser.Text.prototype.setStyle
|
||||
* @param [style] {Object} The style parameters
|
||||
* @param [style.font='bold 20pt Arial'] {String} The style and size of the font
|
||||
* @param [style.fill='black'] {Object} A canvas fillstyle that will be used on the text eg 'red', '#00FF00'
|
||||
* @param [style.align='left'] {String} Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
|
||||
* @param [style.stroke='black'] {String} A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'
|
||||
* @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke)
|
||||
* @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used
|
||||
* @param [style.wordWrapWidth=100] {Number} The width at which text will wrap
|
||||
*/
|
||||
Phaser.Text.prototype.setStyle = function (style) {
|
||||
|
||||
style = style || {};
|
||||
style.font = style.font || 'bold 20pt Arial';
|
||||
style.fill = style.fill || 'black';
|
||||
style.align = style.align || 'left';
|
||||
style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
|
||||
style.strokeThickness = style.strokeThickness || 0;
|
||||
style.wordWrap = style.wordWrap || false;
|
||||
style.wordWrapWidth = style.wordWrapWidth || 100;
|
||||
style.shadowOffsetX = style.shadowOffsetX || 0;
|
||||
style.shadowOffsetY = style.shadowOffsetY || 0;
|
||||
style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
|
||||
style.shadowBlur = style.shadowBlur || 0;
|
||||
|
||||
this.style = style;
|
||||
this.dirty = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
|
||||
*
|
||||
* @method Phaser.Text.prototype.updateText
|
||||
* @private
|
||||
*/
|
||||
Phaser.Text.prototype.updateText = function () {
|
||||
|
||||
this.context.font = this.style.font;
|
||||
|
||||
var outputText = this.text;
|
||||
|
||||
// word wrap
|
||||
// preserve original text
|
||||
if (this.style.wordWrap)
|
||||
{
|
||||
outputText = this.runWordWrap(this.text);
|
||||
}
|
||||
|
||||
//split text into lines
|
||||
var lines = outputText.split(/(?:\r\n|\r|\n)/);
|
||||
|
||||
//calculate text width
|
||||
var lineWidths = [];
|
||||
var maxLineWidth = 0;
|
||||
|
||||
for (var i = 0; i < lines.length; i++)
|
||||
{
|
||||
var lineWidth = this.context.measureText(lines[i]).width;
|
||||
lineWidths[i] = lineWidth;
|
||||
maxLineWidth = Math.max(maxLineWidth, lineWidth);
|
||||
}
|
||||
|
||||
this.canvas.width = maxLineWidth + this.style.strokeThickness;
|
||||
|
||||
//calculate text height
|
||||
var lineHeight = this.determineFontHeight('font: ' + this.style.font + ';') + this.style.strokeThickness + this._lineSpacing + this.style.shadowOffsetY;
|
||||
|
||||
this.canvas.height = lineHeight * lines.length;
|
||||
|
||||
if (navigator.isCocoonJS)
|
||||
{
|
||||
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
|
||||
}
|
||||
|
||||
//set canvas text styles
|
||||
this.context.fillStyle = this.style.fill;
|
||||
this.context.font = this.style.font;
|
||||
|
||||
this.context.strokeStyle = this.style.stroke;
|
||||
this.context.lineWidth = this.style.strokeThickness;
|
||||
|
||||
this.context.shadowOffsetX = this.style.shadowOffsetX;
|
||||
this.context.shadowOffsetY = this.style.shadowOffsetY;
|
||||
this.context.shadowColor = this.style.shadowColor;
|
||||
this.context.shadowBlur = this.style.shadowBlur;
|
||||
|
||||
this.context.textBaseline = 'top';
|
||||
this.context.lineCap = 'round';
|
||||
this.context.lineJoin = 'round';
|
||||
|
||||
//draw lines line by line
|
||||
for (i = 0; i < lines.length; i++)
|
||||
{
|
||||
var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight);
|
||||
|
||||
if (this.style.align === 'right')
|
||||
{
|
||||
linePosition.x += maxLineWidth - lineWidths[i];
|
||||
}
|
||||
else if (this.style.align === 'center')
|
||||
{
|
||||
linePosition.x += (maxLineWidth - lineWidths[i]) / 2;
|
||||
}
|
||||
|
||||
linePosition.y += this._lineSpacing;
|
||||
|
||||
if (this.style.stroke && this.style.strokeThickness)
|
||||
{
|
||||
this.context.strokeText(lines[i], linePosition.x, linePosition.y);
|
||||
}
|
||||
|
||||
if (this.style.fill)
|
||||
{
|
||||
this.context.fillText(lines[i], linePosition.x, linePosition.y);
|
||||
}
|
||||
}
|
||||
|
||||
this.updateTexture();
|
||||
};
|
||||
|
||||
/**
|
||||
* Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
|
||||
*
|
||||
* @method Phaser.Text.prototype.runWordWrap
|
||||
* @private
|
||||
*/
|
||||
Phaser.Text.prototype.runWordWrap = function (text) {
|
||||
|
||||
var result = '';
|
||||
var lines = text.split('\n');
|
||||
|
||||
for (var i = 0; i < lines.length; i++)
|
||||
{
|
||||
var spaceLeft = this.style.wordWrapWidth;
|
||||
var words = lines[i].split(' ');
|
||||
|
||||
for (var j = 0; j < words.length; j++)
|
||||
{
|
||||
var wordWidth = this.context.measureText(words[j]).width;
|
||||
var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
|
||||
|
||||
if (wordWidthWithSpace > spaceLeft)
|
||||
{
|
||||
// Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
|
||||
if (j > 0)
|
||||
{
|
||||
result += '\n';
|
||||
}
|
||||
result += words[j] + ' ';
|
||||
spaceLeft = this.style.wordWrapWidth - wordWidth;
|
||||
}
|
||||
else
|
||||
{
|
||||
spaceLeft -= wordWidthWithSpace;
|
||||
result += words[j] + ' ';
|
||||
}
|
||||
}
|
||||
|
||||
if (i < lines.length-1)
|
||||
{
|
||||
result += '\n';
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Indicates the rotation of the Text, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
|
||||
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
|
||||
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead.
|
||||
* @name Phaser.Text#angle
|
||||
* @property {number} angle - Gets or sets the angle of rotation in degrees.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'angle', {
|
||||
|
||||
get: function() {
|
||||
return Phaser.Math.radToDeg(this.rotation);
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
this.rotation = Phaser.Math.degToRad(value);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The text string to be displayed by this Text object, taking into account the style settings.
|
||||
* @name Phaser.Text#text
|
||||
* @property {string} text - The text string to be displayed by this Text object, taking into account the style settings.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'text', {
|
||||
|
||||
get: function() {
|
||||
return this._text;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._text)
|
||||
{
|
||||
this._text = value.toString() || ' ';
|
||||
this.dirty = true;
|
||||
this.updateTransform();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#font
|
||||
* @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'font', {
|
||||
|
||||
get: function() {
|
||||
return this._font;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._font)
|
||||
{
|
||||
this._font = value.trim();
|
||||
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
|
||||
this.dirty = true;
|
||||
this.updateTransform();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#fontSize
|
||||
* @property {number} fontSize - The size of the font in pixels.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
|
||||
|
||||
get: function() {
|
||||
return this._fontSize;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
value = parseInt(value, 10);
|
||||
|
||||
if (value !== this._fontSize)
|
||||
{
|
||||
this._fontSize = value;
|
||||
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
|
||||
this.dirty = true;
|
||||
this.updateTransform();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#fontWeight
|
||||
* @property {number} fontWeight - The weight of the font: 'normal', 'bold', 'italic'. You can combine settings too, such as 'bold italic'.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
|
||||
|
||||
get: function() {
|
||||
return this._fontWeight;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._fontWeight)
|
||||
{
|
||||
this._fontWeight = value;
|
||||
this.style.font = this._fontWeight + ' ' + this._fontSize + "px '" + this._font + "'";
|
||||
this.dirty = true;
|
||||
this.updateTransform();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#fill
|
||||
* @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'fill', {
|
||||
|
||||
get: function() {
|
||||
return this.style.fill;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.fill)
|
||||
{
|
||||
this.style.fill = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#align
|
||||
* @property {string} align - Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'align', {
|
||||
|
||||
get: function() {
|
||||
return this.style.align;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.align)
|
||||
{
|
||||
this.style.align = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#stroke
|
||||
* @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'stroke', {
|
||||
|
||||
get: function() {
|
||||
return this.style.stroke;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.stroke)
|
||||
{
|
||||
this.style.stroke = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#strokeThickness
|
||||
* @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
|
||||
|
||||
get: function() {
|
||||
return this.style.strokeThickness;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.strokeThickness)
|
||||
{
|
||||
this.style.strokeThickness = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#wordWrap
|
||||
* @property {boolean} wordWrap - Indicates if word wrap should be used.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
|
||||
|
||||
get: function() {
|
||||
return this.style.wordWrap;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.wordWrap)
|
||||
{
|
||||
this.style.wordWrap = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#wordWrapWidth
|
||||
* @property {number} wordWrapWidth - The width at which text will wrap.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
|
||||
|
||||
get: function() {
|
||||
return this.style.wordWrapWidth;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.wordWrapWidth)
|
||||
{
|
||||
this.style.wordWrapWidth = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#lineSpacing
|
||||
* @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
|
||||
|
||||
get: function() {
|
||||
return this._lineSpacing;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this._lineSpacing)
|
||||
{
|
||||
this._lineSpacing = parseFloat(value);
|
||||
this.dirty = true;
|
||||
this.updateTransform();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#shadowOffsetX
|
||||
* @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
|
||||
|
||||
get: function() {
|
||||
return this.style.shadowOffsetX;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.shadowOffsetX)
|
||||
{
|
||||
this.style.shadowOffsetX = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#shadowOffsetY
|
||||
* @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
|
||||
|
||||
get: function() {
|
||||
return this.style.shadowOffsetY;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.shadowOffsetY)
|
||||
{
|
||||
this.style.shadowOffsetY = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#shadowColor
|
||||
* @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
|
||||
|
||||
get: function() {
|
||||
return this.style.shadowColor;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.shadowColor)
|
||||
{
|
||||
this.style.shadowColor = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#shadowBlur
|
||||
* @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
|
||||
|
||||
get: function() {
|
||||
return this.style.shadowBlur;
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
if (value !== this.style.shadowBlur)
|
||||
{
|
||||
this.style.shadowBlur = value;
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* By default a Text object won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
|
||||
* activated for this object and it will then start to process click/touch events and more.
|
||||
*
|
||||
* @name Phaser.Text#inputEnabled
|
||||
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, "inputEnabled", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return (this.input && this.input.enabled);
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (this.input === null)
|
||||
{
|
||||
this.input = new Phaser.InputHandler(this);
|
||||
this.input.start();
|
||||
}
|
||||
else if (this.input && !this.input.enabled)
|
||||
{
|
||||
this.input.start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.input && this.input.enabled)
|
||||
{
|
||||
this.input.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* An Text that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Text.cameraOffset.
|
||||
* Note that the cameraOffset values are in addition to any parent in the display list.
|
||||
* So if this Text was in a Group that has x: 200, then this will be added to the cameraOffset.x
|
||||
*
|
||||
* @name Phaser.Text#fixedToCamera
|
||||
* @property {boolean} fixedToCamera - Set to true to fix this Text to the Camera at its current world coordinates.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, "fixedToCamera", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[7];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
this._cache[7] = 1;
|
||||
this.cameraOffset.set(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._cache[7] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Text#destroyPhase
|
||||
* @property {boolean} destroyPhase - True if this object is currently being destroyed.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Text.prototype, "destroyPhase", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[8];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
766
src/gameobjects/TileSprite.js
Normal file
766
src/gameobjects/TileSprite.js
Normal file
@@ -0,0 +1,766 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
|
||||
* Please note that TileSprites, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.
|
||||
*
|
||||
* @class Phaser.TileSprite
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
|
||||
* @param {number} width - The width of the TileSprite.
|
||||
* @param {number} height - The height of the TileSprite.
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
|
||||
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
*/
|
||||
Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
width = width || 256;
|
||||
height = height || 256;
|
||||
key = key || null;
|
||||
frame = frame || null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this Sprite.
|
||||
* @default
|
||||
*/
|
||||
this.name = '';
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @readonly
|
||||
*/
|
||||
this.type = Phaser.TILESPRITE;
|
||||
|
||||
/**
|
||||
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
|
||||
*/
|
||||
this.z = 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
|
||||
*/
|
||||
this.events = new Phaser.Events(this);
|
||||
|
||||
/**
|
||||
* @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
|
||||
*/
|
||||
this.animations = new Phaser.AnimationManager(this);
|
||||
|
||||
/**
|
||||
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
|
||||
*/
|
||||
this.key = key;
|
||||
|
||||
/**
|
||||
* @property {number} _frame - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._frame = 0;
|
||||
|
||||
/**
|
||||
* @property {string} _frameName - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._frameName = '';
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} _scroll - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._scroll = new Phaser.Point();
|
||||
|
||||
PIXI.TilingSprite.call(this, PIXI.TextureCache['__default'], width, height);
|
||||
|
||||
this.loadTexture(key, frame);
|
||||
|
||||
this.position.set(x, y);
|
||||
|
||||
/**
|
||||
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
|
||||
*/
|
||||
this.input = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
|
||||
*/
|
||||
this.world = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* Should this Sprite be automatically culled if out of range of the camera?
|
||||
* A culled sprite has its renderable property set to 'false'.
|
||||
* Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
|
||||
*
|
||||
* @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
|
||||
* @default
|
||||
*/
|
||||
this.autoCull = false;
|
||||
|
||||
/**
|
||||
* If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
|
||||
* and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
|
||||
* bounds every frame to support it, and not all games need it. Enable it by setting the value to true.
|
||||
* @property {boolean} checkWorldBounds
|
||||
* @default
|
||||
*/
|
||||
this.checkWorldBounds = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
|
||||
*/
|
||||
this.cameraOffset = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* By default Sprites won't add themselves to any physics system and their physics body will be `null`.
|
||||
* To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
|
||||
* and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
|
||||
*
|
||||
* Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
|
||||
* If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
|
||||
*
|
||||
* @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
|
||||
* @default
|
||||
*/
|
||||
this.body = null;
|
||||
|
||||
/**
|
||||
* A small internal cache:
|
||||
* 0 = previous position.x
|
||||
* 1 = previous position.y
|
||||
* 2 = previous rotation
|
||||
* 3 = renderID
|
||||
* 4 = fresh? (0 = no, 1 = yes)
|
||||
* 5 = outOfBoundsFired (0 = no, 1 = yes)
|
||||
* 6 = exists (0 = no, 1 = yes)
|
||||
* 7 = fixed to camera (0 = no, 1 = yes)
|
||||
* 8 = destroy phase? (0 = no, 1 = yes)
|
||||
* @property {Array} _cache
|
||||
* @private
|
||||
*/
|
||||
this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0, 0 ];
|
||||
|
||||
};
|
||||
|
||||
Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
|
||||
Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
|
||||
|
||||
/**
|
||||
* Automatically called by World.preUpdate.
|
||||
*
|
||||
* @method Phaser.TileSprite#preUpdate
|
||||
* @memberof Phaser.TileSprite
|
||||
*/
|
||||
Phaser.TileSprite.prototype.preUpdate = function() {
|
||||
|
||||
if (this._cache[4] === 1 && this.exists)
|
||||
{
|
||||
this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
|
||||
this.worldTransform.tx = this.world.x;
|
||||
this.worldTransform.ty = this.world.y;
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (this.body)
|
||||
{
|
||||
this.body.preUpdate();
|
||||
}
|
||||
|
||||
this._cache[4] = 0;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
this._cache[0] = this.world.x;
|
||||
this._cache[1] = this.world.y;
|
||||
this._cache[2] = this.rotation;
|
||||
|
||||
if (!this.exists || !this.parent.exists)
|
||||
{
|
||||
// Reset the renderOrderID
|
||||
this._cache[3] = -1;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Cache the bounds if we need it
|
||||
if (this.autoCull || this.checkWorldBounds)
|
||||
{
|
||||
this._bounds.copyFrom(this.getBounds());
|
||||
}
|
||||
|
||||
if (this.autoCull)
|
||||
{
|
||||
// Won't get rendered but will still get its transform updated
|
||||
this.renderable = this.game.world.camera.screenView.intersects(this._bounds);
|
||||
}
|
||||
|
||||
if (this.checkWorldBounds)
|
||||
{
|
||||
// The Sprite is already out of the world bounds, so let's check to see if it has come back again
|
||||
if (this._cache[5] === 1 && this.game.world.bounds.intersects(this._bounds))
|
||||
{
|
||||
this._cache[5] = 0;
|
||||
this.events.onEnterBounds.dispatch(this);
|
||||
}
|
||||
else if (this._cache[5] === 0 && !this.game.world.bounds.intersects(this._bounds))
|
||||
{
|
||||
// The Sprite WAS in the screen, but has now left.
|
||||
this._cache[5] = 1;
|
||||
this.events.onOutOfBounds.dispatch(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
|
||||
|
||||
if (this.visible)
|
||||
{
|
||||
this._cache[3] = this.game.stage.currentRenderOrderID++;
|
||||
}
|
||||
|
||||
this.animations.update();
|
||||
|
||||
if (this._scroll.x !== 0)
|
||||
{
|
||||
this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
|
||||
}
|
||||
|
||||
if (this._scroll.y !== 0)
|
||||
{
|
||||
this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
|
||||
}
|
||||
|
||||
if (this.body)
|
||||
{
|
||||
this.body.preUpdate();
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].preUpdate();
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Override and use this function in your own custom objects to handle any update requirements you may have.
|
||||
*
|
||||
* @method Phaser.TileSprite#update
|
||||
* @memberof Phaser.TileSprite
|
||||
*/
|
||||
Phaser.TileSprite.prototype.update = function() {
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Internal function called by the World postUpdate cycle.
|
||||
*
|
||||
* @method Phaser.TileSprite#postUpdate
|
||||
* @memberof Phaser.TileSprite
|
||||
*/
|
||||
Phaser.TileSprite.prototype.postUpdate = function() {
|
||||
|
||||
if (this.exists && this.body)
|
||||
{
|
||||
this.body.postUpdate();
|
||||
}
|
||||
|
||||
// Fixed to Camera?
|
||||
if (this._cache[7] === 1)
|
||||
{
|
||||
this.position.x = this.game.camera.view.x + this.cameraOffset.x;
|
||||
this.position.y = this.game.camera.view.y + this.cameraOffset.y;
|
||||
}
|
||||
|
||||
// Update any Children
|
||||
for (var i = 0, len = this.children.length; i < len; i++)
|
||||
{
|
||||
this.children[i].postUpdate();
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
|
||||
* The scroll speed is specified in pixels per second.
|
||||
* A negative x value will scroll to the left. A positive x value will scroll to the right.
|
||||
* A negative y value will scroll up. A positive y value will scroll down.
|
||||
*
|
||||
* @method Phaser.TileSprite#autoScroll
|
||||
* @memberof Phaser.TileSprite
|
||||
*/
|
||||
Phaser.TileSprite.prototype.autoScroll = function(x, y) {
|
||||
|
||||
this._scroll.set(x, y);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Stops an automatically scrolling TileSprite.
|
||||
*
|
||||
* @method Phaser.TileSprite#stopScroll
|
||||
* @memberof Phaser.TileSprite
|
||||
*/
|
||||
Phaser.TileSprite.prototype.stopScroll = function() {
|
||||
|
||||
this._scroll.set(0, 0);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes the Texture the TileSprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
|
||||
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
|
||||
*
|
||||
* @method Phaser.TileSprite#loadTexture
|
||||
* @memberof Phaser.TileSprite
|
||||
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
|
||||
* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
|
||||
*/
|
||||
Phaser.TileSprite.prototype.loadTexture = function (key, frame) {
|
||||
|
||||
frame = frame || 0;
|
||||
|
||||
if (key instanceof Phaser.RenderTexture)
|
||||
{
|
||||
this.key = key.key;
|
||||
this.setTexture(key);
|
||||
return;
|
||||
}
|
||||
else if (key instanceof Phaser.BitmapData)
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(key.texture);
|
||||
return;
|
||||
}
|
||||
else if (key instanceof PIXI.Texture)
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(key);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (key === null || typeof key === 'undefined')
|
||||
{
|
||||
this.key = '__default';
|
||||
this.setTexture(PIXI.TextureCache[this.key]);
|
||||
return;
|
||||
}
|
||||
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
|
||||
{
|
||||
this.key = '__missing';
|
||||
this.setTexture(PIXI.TextureCache[this.key]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.game.cache.isSpriteSheet(key))
|
||||
{
|
||||
this.key = key;
|
||||
|
||||
// var frameData = this.game.cache.getFrameData(key);
|
||||
this.animations.loadFrameData(this.game.cache.getFrameData(key));
|
||||
|
||||
if (typeof frame === 'string')
|
||||
{
|
||||
this.frameName = frame;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.frame = frame;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.key = key;
|
||||
this.setTexture(PIXI.TextureCache[key]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
|
||||
* and nulls its reference to game, freeing it up for garbage collection.
|
||||
*
|
||||
* @method Phaser.TileSprite#destroy
|
||||
* @memberof Phaser.TileSprite
|
||||
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
|
||||
*/
|
||||
Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
|
||||
|
||||
if (this.game === null || this.destroyPhase) { return; }
|
||||
|
||||
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
|
||||
|
||||
this._cache[8] = 1;
|
||||
|
||||
if (this.filters)
|
||||
{
|
||||
this.filters = null;
|
||||
}
|
||||
|
||||
if (this.parent)
|
||||
{
|
||||
if (this.parent instanceof Phaser.Group)
|
||||
{
|
||||
this.parent.remove(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.parent.removeChild(this);
|
||||
}
|
||||
}
|
||||
|
||||
this.animations.destroy();
|
||||
|
||||
this.events.destroy();
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
if (destroyChildren)
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.children[i].destroy(destroyChildren);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (i--)
|
||||
{
|
||||
this.removeChild(this.children[i]);
|
||||
}
|
||||
}
|
||||
|
||||
this.exists = false;
|
||||
this.visible = false;
|
||||
|
||||
this.filters = null;
|
||||
this.mask = null;
|
||||
this.game = null;
|
||||
|
||||
this._cache[8] = 0;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
|
||||
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
|
||||
*
|
||||
* @method Phaser.TileSprite#play
|
||||
* @memberof Phaser.TileSprite
|
||||
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
|
||||
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
|
||||
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
|
||||
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
|
||||
* @return {Phaser.Animation} A reference to playing Animation instance.
|
||||
*/
|
||||
Phaser.TileSprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
|
||||
|
||||
return this.animations.play(name, frameRate, loop, killOnComplete);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
|
||||
* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
|
||||
* If the TileSprite has a physics body that too is reset.
|
||||
*
|
||||
* @method Phaser.TileSprite#reset
|
||||
* @memberof Phaser.TileSprite
|
||||
* @param {number} x - The x coordinate (in world space) to position the Sprite at.
|
||||
* @param {number} y - The y coordinate (in world space) to position the Sprite at.
|
||||
* @return (Phaser.TileSprite) This instance.
|
||||
*/
|
||||
Phaser.TileSprite.prototype.reset = function(x, y) {
|
||||
|
||||
this.world.setTo(x, y);
|
||||
this.position.x = x;
|
||||
this.position.y = y;
|
||||
this.alive = true;
|
||||
this.exists = true;
|
||||
this.visible = true;
|
||||
this.renderable = true;
|
||||
this._outOfBoundsFired = false;
|
||||
|
||||
this.tilePosition.x = 0;
|
||||
this.tilePosition.y = 0;
|
||||
|
||||
if (this.body)
|
||||
{
|
||||
this.body.reset(x, y, false, false);
|
||||
}
|
||||
|
||||
this._cache[4] = 1;
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
|
||||
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
|
||||
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
|
||||
*
|
||||
* @name Phaser.TileSprite#angle
|
||||
* @property {number} angle - The angle of this Sprite in degrees.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "angle", {
|
||||
|
||||
get: function() {
|
||||
|
||||
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
|
||||
|
||||
},
|
||||
|
||||
set: function(value) {
|
||||
|
||||
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.TileSprite#frame
|
||||
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "frame", {
|
||||
|
||||
get: function () {
|
||||
return this.animations.frame;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value !== this.animations.frame)
|
||||
{
|
||||
this.animations.frame = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.TileSprite#frameName
|
||||
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "frameName", {
|
||||
|
||||
get: function () {
|
||||
return this.animations.frameName;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value !== this.animations.frameName)
|
||||
{
|
||||
this.animations.frameName = value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* An TileSprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in TileSprite.cameraOffset.
|
||||
* Note that the cameraOffset values are in addition to any parent in the display list.
|
||||
* So if this TileSprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
|
||||
*
|
||||
* @name Phaser.TileSprite#fixedToCamera
|
||||
* @property {boolean} fixedToCamera - Set to true to fix this TileSprite to the Camera at its current world coordinates.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "fixedToCamera", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[7];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
this._cache[7] = 1;
|
||||
this.cameraOffset.set(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
this._cache[7] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* TileSprite.exists controls if the core game loop and physics update this TileSprite or not.
|
||||
* When you set TileSprite.exists to false it will remove its Body from the physics world (if it has one) and also set TileSprite.visible to false.
|
||||
* Setting TileSprite.exists to true will re-add the Body to the physics world (if it has a body) and set TileSprite.visible to true.
|
||||
*
|
||||
* @name Phaser.TileSprite#exists
|
||||
* @property {boolean} exists - If the TileSprite is processed by the core game update and physics.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "exists", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[6];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
// exists = true
|
||||
this._cache[6] = 1;
|
||||
|
||||
if (this.body && this.body.type === Phaser.Physics.P2JS)
|
||||
{
|
||||
this.body.addToWorld();
|
||||
}
|
||||
|
||||
this.visible = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// exists = false
|
||||
this._cache[6] = 0;
|
||||
|
||||
if (this.body && this.body.type === Phaser.Physics.P2JS)
|
||||
{
|
||||
this.body.safeRemove = true;
|
||||
}
|
||||
|
||||
this.visible = false;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* By default a TileSprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
|
||||
* activated for this object and it will then start to process click/touch events and more.
|
||||
*
|
||||
* @name Phaser.TileSprite#inputEnabled
|
||||
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "inputEnabled", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return (this.input && this.input.enabled);
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (this.input === null)
|
||||
{
|
||||
this.input = new Phaser.InputHandler(this);
|
||||
this.input.start();
|
||||
}
|
||||
else if (this.input && !this.input.enabled)
|
||||
{
|
||||
this.input.start();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.input && this.input.enabled)
|
||||
{
|
||||
this.input.stop();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The position of the TileSprite on the x axis relative to the local coordinates of the parent.
|
||||
*
|
||||
* @name Phaser.TileSprite#x
|
||||
* @property {number} x - The position of the TileSprite on the x axis relative to the local coordinates of the parent.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.position.x;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.position.x = value;
|
||||
|
||||
if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
|
||||
{
|
||||
this.body._reset = 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The position of the TileSprite on the y axis relative to the local coordinates of the parent.
|
||||
*
|
||||
* @name Phaser.TileSprite#y
|
||||
* @property {number} y - The position of the TileSprite on the y axis relative to the local coordinates of the parent.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.position.y;
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.position.y = value;
|
||||
|
||||
if (this.body && this.body.type === Phaser.Physics.ARCADE && this.body.phase === 2)
|
||||
{
|
||||
this.body._reset = 1;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.TileSprite#destroyPhase
|
||||
* @property {boolean} destroyPhase - True if this object is currently being destroyed.
|
||||
*/
|
||||
Object.defineProperty(Phaser.TileSprite.prototype, "destroyPhase", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return !!this._cache[8];
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
536
src/geom/Circle.js
Normal file
536
src/geom/Circle.js
Normal file
@@ -0,0 +1,536 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
|
||||
* @class Circle
|
||||
* @classdesc Phaser - Circle
|
||||
* @constructor
|
||||
* @param {number} [x=0] - The x coordinate of the center of the circle.
|
||||
* @param {number} [y=0] - The y coordinate of the center of the circle.
|
||||
* @param {number} [diameter=0] - The diameter of the circle.
|
||||
* @return {Phaser.Circle} This circle object
|
||||
*/
|
||||
Phaser.Circle = function (x, y, diameter) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
diameter = diameter || 0;
|
||||
|
||||
/**
|
||||
* @property {number} x - The x coordinate of the center of the circle.
|
||||
*/
|
||||
this.x = x;
|
||||
|
||||
/**
|
||||
* @property {number} y - The y coordinate of the center of the circle.
|
||||
*/
|
||||
this.y = y;
|
||||
|
||||
/**
|
||||
* @property {number} _diameter - The diameter of the circle.
|
||||
* @private
|
||||
*/
|
||||
this._diameter = diameter;
|
||||
|
||||
if (diameter > 0)
|
||||
{
|
||||
/**
|
||||
* @property {number} _radius - The radius of the circle.
|
||||
* @private
|
||||
*/
|
||||
this._radius = diameter * 0.5;
|
||||
}
|
||||
else
|
||||
{
|
||||
this._radius = 0;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Circle.prototype = {
|
||||
|
||||
/**
|
||||
* The circumference of the circle.
|
||||
* @method Phaser.Circle#circumference
|
||||
* @return {number}
|
||||
*/
|
||||
circumference: function () {
|
||||
return 2 * (Math.PI * this._radius);
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the members of Circle to the specified values.
|
||||
* @method Phaser.Circle#setTo
|
||||
* @param {number} x - The x coordinate of the center of the circle.
|
||||
* @param {number} y - The y coordinate of the center of the circle.
|
||||
* @param {number} diameter - The diameter of the circle in pixels.
|
||||
* @return {Circle} This circle object.
|
||||
*/
|
||||
setTo: function (x, y, diameter) {
|
||||
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this._diameter = diameter;
|
||||
this._radius = diameter * 0.5;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y and diameter properties from any given object to this Circle.
|
||||
* @method Phaser.Circle#copyFrom
|
||||
* @param {any} source - The object to copy from.
|
||||
* @return {Circle} This Circle object.
|
||||
*/
|
||||
copyFrom: function (source) {
|
||||
|
||||
return this.setTo(source.x, source.y, source.diameter);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y and diameter properties from this Circle to any given object.
|
||||
* @method Phaser.Circle#copyTo
|
||||
* @param {any} dest - The object to copy to.
|
||||
* @return {Object} This dest object.
|
||||
*/
|
||||
copyTo: function (dest) {
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
dest.diameter = this._diameter;
|
||||
|
||||
return dest;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the distance from the center of the Circle object to the given object
|
||||
* (can be Circle, Point or anything with x/y properties)
|
||||
* @method Phaser.Circle#distance
|
||||
* @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
|
||||
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
|
||||
* @return {number} The distance between this Point object and the destination Point object.
|
||||
*/
|
||||
distance: function (dest, round) {
|
||||
|
||||
if (typeof round === "undefined") { round = false; }
|
||||
|
||||
if (round)
|
||||
{
|
||||
return Phaser.Math.distanceRounded(this.x, this.y, dest.x, dest.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
|
||||
* @method Phaser.Circle#clone
|
||||
* @param {Phaser.Circle} out - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
|
||||
* @return {Phaser.Circle} The cloned Circle object.
|
||||
*/
|
||||
clone: function (out) {
|
||||
|
||||
if (typeof out === "undefined")
|
||||
{
|
||||
out = new Phaser.Circle(this.x, this.y, this.diameter);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.setTo(this.x, this.y, this.diameter);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Return true if the given x/y coordinates are within this Circle object.
|
||||
* @method Phaser.Circle#contains
|
||||
* @param {number} x - The X value of the coordinate to test.
|
||||
* @param {number} y - The Y value of the coordinate to test.
|
||||
* @return {boolean} True if the coordinates are within this circle, otherwise false.
|
||||
*/
|
||||
contains: function (x, y) {
|
||||
|
||||
return Phaser.Circle.contains(this, x, y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
|
||||
* @method Phaser.Circle#circumferencePoint
|
||||
* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
|
||||
* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
|
||||
* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
|
||||
* @return {Phaser.Point} The Point object holding the result.
|
||||
*/
|
||||
circumferencePoint: function (angle, asDegrees, out) {
|
||||
|
||||
return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
|
||||
* @method Phaser.Circle#offset
|
||||
* @param {number} dx - Moves the x value of the Circle object by this amount.
|
||||
* @param {number} dy - Moves the y value of the Circle object by this amount.
|
||||
* @return {Circle} This Circle object.
|
||||
*/
|
||||
offset: function (dx, dy) {
|
||||
|
||||
this.x += dx;
|
||||
this.y += dy;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
|
||||
* @method Phaser.Circle#offsetPoint
|
||||
* @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
|
||||
* @return {Circle} This Circle object.
|
||||
*/
|
||||
offsetPoint: function (point) {
|
||||
return this.offset(point.x, point.y);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object.
|
||||
* @method Phaser.Circle#toString
|
||||
* @return {string} a string representation of the instance.
|
||||
*/
|
||||
toString: function () {
|
||||
return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Circle.prototype.constructor = Phaser.Circle;
|
||||
|
||||
/**
|
||||
* The largest distance between any two points on the circle. The same as the radius * 2.
|
||||
* @name Phaser.Circle#diameter
|
||||
* @property {number} diameter - Gets or sets the diameter of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "diameter", {
|
||||
|
||||
get: function () {
|
||||
return this._diameter;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value > 0)
|
||||
{
|
||||
this._diameter = value;
|
||||
this._radius = value * 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
|
||||
* @name Phaser.Circle#radius
|
||||
* @property {number} radius - Gets or sets the radius of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "radius", {
|
||||
|
||||
get: function () {
|
||||
return this._radius;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value > 0)
|
||||
{
|
||||
this._radius = value;
|
||||
this._diameter = value * 2;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
|
||||
* @name Phaser.Circle#left
|
||||
* @propety {number} left - Gets or sets the value of the leftmost point of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "left", {
|
||||
|
||||
get: function () {
|
||||
return this.x - this._radius;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value > this.x)
|
||||
{
|
||||
this._radius = 0;
|
||||
this._diameter = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.radius = this.x - value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
|
||||
* @name Phaser.Circle#right
|
||||
* @property {number} right - Gets or sets the value of the rightmost point of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.x + this._radius;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value < this.x)
|
||||
{
|
||||
this._radius = 0;
|
||||
this._diameter = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.radius = value - this.x;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
|
||||
* @name Phaser.Circle#top
|
||||
* @property {number} top - Gets or sets the top of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "top", {
|
||||
|
||||
get: function () {
|
||||
return this.y - this._radius;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value > this.y)
|
||||
{
|
||||
this._radius = 0;
|
||||
this._diameter = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.radius = this.y - value;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
|
||||
* @name Phaser.Circle#bottom
|
||||
* @property {number} bottom - Gets or sets the bottom of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.y + this._radius;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value < this.y)
|
||||
{
|
||||
this._radius = 0;
|
||||
this._diameter = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.radius = value - this.y;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The area of this Circle.
|
||||
* @name Phaser.Circle#area
|
||||
* @property {number} area - The area of this circle.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "area", {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this._radius > 0)
|
||||
{
|
||||
return Math.PI * this._radius * this._radius;
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
|
||||
* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0.
|
||||
* @name Phaser.Circle#empty
|
||||
* @property {boolean} empty - Gets or sets the empty state of the circle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Circle.prototype, "empty", {
|
||||
|
||||
get: function () {
|
||||
return (this._diameter === 0);
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value === true)
|
||||
{
|
||||
this.setTo(0, 0, 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Return true if the given x/y coordinates are within the Circle object.
|
||||
* @method Phaser.Circle.contains
|
||||
* @param {Phaser.Circle} a - The Circle to be checked.
|
||||
* @param {number} x - The X value of the coordinate to test.
|
||||
* @param {number} y - The Y value of the coordinate to test.
|
||||
* @return {boolean} True if the coordinates are within this circle, otherwise false.
|
||||
*/
|
||||
Phaser.Circle.contains = function (a, x, y) {
|
||||
|
||||
// Check if x/y are within the bounds first
|
||||
if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
|
||||
{
|
||||
var dx = (a.x - x) * (a.x - x);
|
||||
var dy = (a.y - y) * (a.y - y);
|
||||
|
||||
return (dx + dy) <= (a.radius * a.radius);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
|
||||
* @method Phaser.Circle.equals
|
||||
* @param {Phaser.Circle} a - The first Circle object.
|
||||
* @param {Phaser.Circle} b - The second Circle object.
|
||||
* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
|
||||
*/
|
||||
Phaser.Circle.equals = function (a, b) {
|
||||
return (a.x == b.x && a.y == b.y && a.diameter == b.diameter);
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the two Circle objects intersect.
|
||||
* This method checks the radius distances between the two Circle objects to see if they intersect.
|
||||
* @method Phaser.Circle.intersects
|
||||
* @param {Phaser.Circle} a - The first Circle object.
|
||||
* @param {Phaser.Circle} b - The second Circle object.
|
||||
* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
|
||||
*/
|
||||
Phaser.Circle.intersects = function (a, b) {
|
||||
return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
|
||||
* @method Phaser.Circle.circumferencePoint
|
||||
* @param {Phaser.Circle} a - The first Circle object.
|
||||
* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
|
||||
* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
|
||||
* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
|
||||
* @return {Phaser.Point} The Point object holding the result.
|
||||
*/
|
||||
Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
|
||||
|
||||
if (typeof asDegrees === "undefined") { asDegrees = false; }
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
if (asDegrees === true)
|
||||
{
|
||||
angle = Phaser.Math.degToRad(angle);
|
||||
}
|
||||
|
||||
out.x = a.x + a.radius * Math.cos(angle);
|
||||
out.y = a.y + a.radius * Math.sin(angle);
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if the given Circle and Rectangle objects intersect.
|
||||
* @method Phaser.Circle.intersectsRectangle
|
||||
* @param {Phaser.Circle} c - The Circle object to test.
|
||||
* @param {Phaser.Rectangle} r - The Rectangle object to test.
|
||||
* @return {boolean} True if the two objects intersect, otherwise false.
|
||||
*/
|
||||
Phaser.Circle.intersectsRectangle = function (c, r) {
|
||||
|
||||
var cx = Math.abs(c.x - r.x - r.halfWidth);
|
||||
var xDist = r.halfWidth + c.radius;
|
||||
|
||||
if (cx > xDist)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var cy = Math.abs(c.y - r.y - r.halfHeight);
|
||||
var yDist = r.halfHeight + c.radius;
|
||||
|
||||
if (cy > yDist)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cx <= r.halfWidth || cy <= r.halfHeight)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var xCornerDist = cx - r.halfWidth;
|
||||
var yCornerDist = cy - r.halfHeight;
|
||||
var xCornerDistSq = xCornerDist * xCornerDist;
|
||||
var yCornerDistSq = yCornerDist * yCornerDist;
|
||||
var maxCornerDistSq = c.radius * c.radius;
|
||||
|
||||
return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
|
||||
|
||||
};
|
||||
|
||||
// Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
|
||||
PIXI.Circle = Phaser.Circle;
|
||||
296
src/geom/Ellipse.js
Normal file
296
src/geom/Ellipse.js
Normal file
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @author Chad Engler <chad@pantherdev.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a Ellipse object. A curve on a plane surrounding two focal points.
|
||||
* @class Ellipse
|
||||
* @classdesc Phaser - Ellipse
|
||||
* @constructor
|
||||
* @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
* @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
* @param {number} [width=0] - The overall width of this ellipse.
|
||||
* @param {number} [height=0] - The overall height of this ellipse.
|
||||
* @return {Phaser.Ellipse} This Ellipse object
|
||||
*/
|
||||
Phaser.Ellipse = function (x, y, width, height) {
|
||||
|
||||
this.type = Phaser.ELLIPSE;
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
width = width || 0;
|
||||
height = height || 0;
|
||||
|
||||
/**
|
||||
* @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
*/
|
||||
this.x = x;
|
||||
|
||||
/**
|
||||
* @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
*/
|
||||
this.y = y;
|
||||
|
||||
/**
|
||||
* @property {number} width - The overall width of this ellipse.
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - The overall height of this ellipse.
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Ellipse.prototype = {
|
||||
|
||||
/**
|
||||
* Sets the members of the Ellipse to the specified values.
|
||||
* @method Phaser.Ellipse#setTo
|
||||
* @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
* @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
|
||||
* @param {number} width - The overall width of this ellipse.
|
||||
* @param {number} height - The overall height of this ellipse.
|
||||
* @return {Phaser.Ellipse} This Ellipse object.
|
||||
*/
|
||||
setTo: function (x, y, width, height) {
|
||||
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y, width and height properties from any given object to this Ellipse.
|
||||
* @method Phaser.Ellipse#copyFrom
|
||||
* @param {any} source - The object to copy from.
|
||||
* @return {Phaser.Ellipse} This Ellipse object.
|
||||
*/
|
||||
copyFrom: function (source) {
|
||||
|
||||
return this.setTo(source.x, source.y, source.width, source.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y and diameter properties from this Circle to any given object.
|
||||
* @method Phaser.Ellipse#copyTo
|
||||
* @param {any} dest - The object to copy to.
|
||||
* @return {Object} This dest object.
|
||||
*/
|
||||
copyTo: function(dest) {
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
dest.width = this.width;
|
||||
dest.height = this.height;
|
||||
|
||||
return dest;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
|
||||
* @method Phaser.Ellipse#clone
|
||||
* @param {Phaser.Ellipse} out - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
|
||||
* @return {Phaser.Ellipse} The cloned Ellipse object.
|
||||
*/
|
||||
clone: function(out) {
|
||||
|
||||
if (typeof out === "undefined")
|
||||
{
|
||||
out = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
out.setTo(this.x, this.y, this.width, this.height);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Return true if the given x/y coordinates are within this Ellipse object.
|
||||
* @method Phaser.Ellipse#contains
|
||||
* @param {number} x - The X value of the coordinate to test.
|
||||
* @param {number} y - The Y value of the coordinate to test.
|
||||
* @return {boolean} True if the coordinates are within this ellipse, otherwise false.
|
||||
*/
|
||||
contains: function (x, y) {
|
||||
|
||||
return Phaser.Ellipse.contains(this, x, y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object.
|
||||
* @method Phaser.Ellipse#toString
|
||||
* @return {string} A string representation of the instance.
|
||||
*/
|
||||
toString: function () {
|
||||
return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
|
||||
|
||||
/**
|
||||
* The left coordinate of the Ellipse. The same as the X coordinate.
|
||||
* @name Phaser.Ellipse#left
|
||||
* @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Ellipse.prototype, "left", {
|
||||
|
||||
get: function () {
|
||||
return this.x;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.x = value;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width.
|
||||
* @name Phaser.Ellipse#right
|
||||
* @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Ellipse.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.x + this.width;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value < this.x)
|
||||
{
|
||||
this.width = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.width = this.x + value;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The top of the Ellipse. The same as its y property.
|
||||
* @name Phaser.Ellipse#top
|
||||
* @property {number} top - Gets or sets the top of the ellipse.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Ellipse.prototype, "top", {
|
||||
|
||||
get: function () {
|
||||
return this.y;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.y = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height.
|
||||
* @name Phaser.Ellipse#bottom
|
||||
* @property {number} bottom - Gets or sets the bottom of the ellipse.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.y + this.height;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value < this.y)
|
||||
{
|
||||
this.height = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.height = this.y + value;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false.
|
||||
* If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0.
|
||||
* @name Phaser.Ellipse#empty
|
||||
* @property {boolean} empty - Gets or sets the empty state of the ellipse.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
|
||||
|
||||
get: function () {
|
||||
return (this.width === 0 || this.height === 0);
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value === true)
|
||||
{
|
||||
this.setTo(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Return true if the given x/y coordinates are within the Ellipse object.
|
||||
* @method Phaser.Ellipse.contains
|
||||
* @param {Phaser.Ellipse} a - The Ellipse to be checked.
|
||||
* @param {number} x - The X value of the coordinate to test.
|
||||
* @param {number} y - The Y value of the coordinate to test.
|
||||
* @return {boolean} True if the coordinates are within this ellipse, otherwise false.
|
||||
*/
|
||||
Phaser.Ellipse.contains = function (a, x, y) {
|
||||
|
||||
if (a.width <= 0 || a.height <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
|
||||
var normx = ((x - a.x) / a.width) - 0.5;
|
||||
var normy = ((y - a.y) / a.height) - 0.5;
|
||||
|
||||
normx *= normx;
|
||||
normy *= normy;
|
||||
|
||||
return (normx + normy < 0.25);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
|
||||
*
|
||||
* @method Phaser.Ellipse.getBounds
|
||||
* @return {Phaser.Rectangle} The framing rectangle
|
||||
*/
|
||||
Phaser.Ellipse.prototype.getBounds = function() {
|
||||
|
||||
return new Phaser.Rectangle(this.x, this.y, this.width, this.height);
|
||||
|
||||
};
|
||||
|
||||
// Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
|
||||
PIXI.Ellipse = Phaser.Ellipse;
|
||||
413
src/geom/Line.js
Normal file
413
src/geom/Line.js
Normal file
@@ -0,0 +1,413 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Line object with a start and an end point.
|
||||
* @class Line
|
||||
* @classdesc Phaser - Line
|
||||
* @constructor
|
||||
* @param {number} [x1=0] - The x coordinate of the start of the line.
|
||||
* @param {number} [y1=0] - The y coordinate of the start of the line.
|
||||
* @param {number} [x2=0] - The x coordinate of the end of the line.
|
||||
* @param {number} [y2=0] - The y coordinate of the end of the line.
|
||||
* @return {Phaser.Line} This line object
|
||||
*/
|
||||
Phaser.Line = function (x1, y1, x2, y2) {
|
||||
|
||||
x1 = x1 || 0;
|
||||
y1 = y1 || 0;
|
||||
x2 = x2 || 0;
|
||||
y2 = y2 || 0;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} start - The start point of the line.
|
||||
*/
|
||||
this.start = new Phaser.Point(x1, y1);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} end - The end point of the line.
|
||||
*/
|
||||
this.end = new Phaser.Point(x2, y2);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Line.prototype = {
|
||||
|
||||
/**
|
||||
* Sets the components of the Line to the specified values.
|
||||
* @method Phaser.Line#setTo
|
||||
* @param {number} [x1=0] - The x coordinate of the start of the line.
|
||||
* @param {number} [y1=0] - The y coordinate of the start of the line.
|
||||
* @param {number} [x2=0] - The x coordinate of the end of the line.
|
||||
* @param {number} [y2=0] - The y coordinate of the end of the line.
|
||||
* @return {Phaser.Line} This line object
|
||||
*/
|
||||
setTo: function (x1, y1, x2, y2) {
|
||||
|
||||
this.start.setTo(x1, y1);
|
||||
this.end.setTo(x2, y2);
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the line to match the x/y coordinates of the two given sprites.
|
||||
* Can optionally be calculated from their center coordinates.
|
||||
* @method Phaser.Line#fromSprite
|
||||
* @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
|
||||
* @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
|
||||
* @param {boolean} [useCenter=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class.
|
||||
* @return {Phaser.Line} This line object
|
||||
*/
|
||||
fromSprite: function (startSprite, endSprite, useCenter) {
|
||||
|
||||
if (typeof useCenter === 'undefined') { useCenter = false; }
|
||||
|
||||
if (useCenter)
|
||||
{
|
||||
return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks for intersection between this line and another Line.
|
||||
* If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
|
||||
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
|
||||
*
|
||||
* @method Phaser.Line#intersects
|
||||
* @param {Phaser.Line} line - The line to check against this one.
|
||||
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
|
||||
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
|
||||
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
|
||||
*/
|
||||
intersects: function (line, asSegment, result) {
|
||||
|
||||
return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
|
||||
* @method Phaser.Line#pointOnLine
|
||||
* @param {number} x - The line to check against this one.
|
||||
* @param {number} y - The line to check against this one.
|
||||
* @return {boolean} True if the point is on the line, false if not.
|
||||
*/
|
||||
pointOnLine: function (x, y) {
|
||||
|
||||
return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
|
||||
* @method Phaser.Line#pointOnSegment
|
||||
* @param {number} x - The line to check against this one.
|
||||
* @param {number} y - The line to check against this one.
|
||||
* @return {boolean} True if the point is on the line and segment, false if not.
|
||||
*/
|
||||
pointOnSegment: function (x, y) {
|
||||
|
||||
var xMin = Math.min(this.start.x, this.end.x);
|
||||
var xMax = Math.max(this.start.x, this.end.x);
|
||||
var yMin = Math.min(this.start.y, this.end.y);
|
||||
var yMax = Math.max(this.start.y, this.end.y);
|
||||
|
||||
return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Using Bresenham's line algorithm this will return an array of all coordinates on this line.
|
||||
* The start and end points are rounded before this runs as the algorithm works on integers.
|
||||
*
|
||||
* @method Phaser.Line#coordinatesOnLine
|
||||
* @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
|
||||
* @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
|
||||
* @return {array} An array of coordinates.
|
||||
*/
|
||||
coordinatesOnLine: function (stepRate, results) {
|
||||
|
||||
if (typeof stepRate === 'undefined') { stepRate = 1; }
|
||||
if (typeof results === 'undefined') { results = []; }
|
||||
|
||||
var x1 = Math.round(this.start.x);
|
||||
var y1 = Math.round(this.start.y);
|
||||
var x2 = Math.round(this.end.x);
|
||||
var y2 = Math.round(this.end.y);
|
||||
|
||||
var dx = Math.abs(x2 - x1);
|
||||
var dy = Math.abs(y2 - y1);
|
||||
var sx = (x1 < x2) ? 1 : -1;
|
||||
var sy = (y1 < y2) ? 1 : -1;
|
||||
var err = dx - dy;
|
||||
|
||||
results.push([x1, y1]);
|
||||
|
||||
var i = 1;
|
||||
|
||||
while (!((x1 == x2) && (y1 == y2)))
|
||||
{
|
||||
var e2 = err << 1;
|
||||
|
||||
if (e2 > -dy)
|
||||
{
|
||||
err -= dy;
|
||||
x1 += sx;
|
||||
}
|
||||
|
||||
if (e2 < dx)
|
||||
{
|
||||
err += dx;
|
||||
y1 += sy;
|
||||
}
|
||||
|
||||
if (i % stepRate === 0)
|
||||
{
|
||||
results.push([x1, y1]);
|
||||
}
|
||||
|
||||
i++;
|
||||
|
||||
}
|
||||
|
||||
return results;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#length
|
||||
* @property {number} length - Gets the length of the line segment.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "length", {
|
||||
|
||||
get: function () {
|
||||
return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#angle
|
||||
* @property {number} angle - Gets the angle of the line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "angle", {
|
||||
|
||||
get: function () {
|
||||
return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#slope
|
||||
* @property {number} slope - Gets the slope of the line (y/x).
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "slope", {
|
||||
|
||||
get: function () {
|
||||
return (this.end.y - this.start.y) / (this.end.x - this.start.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#perpSlope
|
||||
* @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
|
||||
|
||||
get: function () {
|
||||
return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#x
|
||||
* @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return Math.min(this.start.x, this.end.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#y
|
||||
* @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return Math.min(this.start.y, this.end.y);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#left
|
||||
* @property {number} left - Gets the left-most point of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "left", {
|
||||
|
||||
get: function () {
|
||||
return Math.min(this.start.x, this.end.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#right
|
||||
* @property {number} right - Gets the right-most point of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return Math.max(this.start.x, this.end.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#top
|
||||
* @property {number} top - Gets the top-most point of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "top", {
|
||||
|
||||
get: function () {
|
||||
return Math.min(this.start.y, this.end.y);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#bottom
|
||||
* @property {number} bottom - Gets the bottom-most point of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return Math.max(this.start.y, this.end.y);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#width
|
||||
* @property {number} width - Gets the width of this bounds of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "width", {
|
||||
|
||||
get: function () {
|
||||
return Math.abs(this.start.x - this.end.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Line#height
|
||||
* @property {number} height - Gets the height of this bounds of this line.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Line.prototype, "height", {
|
||||
|
||||
get: function () {
|
||||
return Math.abs(this.start.y - this.end.y);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Checks for intersection between two lines as defined by the given start and end points.
|
||||
* If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
|
||||
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
|
||||
* Adapted from code by Keith Hair
|
||||
*
|
||||
* @method Phaser.Line.intersectsPoints
|
||||
* @param {Phaser.Point} a - The start of the first Line to be checked.
|
||||
* @param {Phaser.Point} b - The end of the first line to be checked.
|
||||
* @param {Phaser.Point} e - The start of the second Line to be checked.
|
||||
* @param {Phaser.Point} f - The end of the second line to be checked.
|
||||
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
|
||||
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
|
||||
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
|
||||
*/
|
||||
Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
|
||||
|
||||
if (typeof asSegment === 'undefined') { asSegment = true; }
|
||||
if (typeof result === 'undefined') { result = new Phaser.Point(); }
|
||||
|
||||
var a1 = b.y - a.y;
|
||||
var a2 = f.y - e.y;
|
||||
var b1 = a.x - b.x;
|
||||
var b2 = e.x - f.x;
|
||||
var c1 = (b.x * a.y) - (a.x * b.y);
|
||||
var c2 = (f.x * e.y) - (e.x * f.y);
|
||||
var denom = (a1 * b2) - (a2 * b1);
|
||||
|
||||
if (denom === 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
result.x = ((b1 * c2) - (b2 * c1)) / denom;
|
||||
result.y = ((a2 * c1) - (a1 * c2)) / denom;
|
||||
|
||||
if (asSegment)
|
||||
{
|
||||
if ( result.x < Math.min(a.x, b.x) || result.x > Math.max(a.x, b.x) ||
|
||||
result.y < Math.min(a.y, b.y) || result.y > Math.max(a.y, b.y) ||
|
||||
result.x < Math.min(e.x, f.x) || result.x > Math.max(e.x, f.x) ||
|
||||
result.y < Math.min(e.y, f.y) || result.y > Math.max(e.y, f.y) ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks for intersection between two lines.
|
||||
* If asSegment is true it will check for segment intersection.
|
||||
* If asSegment is false it will check for line intersection.
|
||||
* Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
|
||||
* Adapted from code by Keith Hair
|
||||
*
|
||||
* @method Phaser.Line.intersects
|
||||
* @param {Phaser.Line} a - The first Line to be checked.
|
||||
* @param {Phaser.Line} b - The second Line to be checked.
|
||||
* @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
|
||||
* @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
|
||||
* @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
|
||||
*/
|
||||
Phaser.Line.intersects = function (a, b, asSegment, result) {
|
||||
|
||||
return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
|
||||
|
||||
};
|
||||
872
src/geom/Point.js
Normal file
872
src/geom/Point.js
Normal file
@@ -0,0 +1,872 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Point
|
||||
* @classdesc
|
||||
* The Point object represents a location in a two-dimensional coordinate system,
|
||||
* where x represents the horizontal axis and y represents the vertical axis.
|
||||
* The following code creates a point at (0,0):
|
||||
* `var myPoint = new Phaser.Point();`
|
||||
* You can also use them as 2D Vectors and you'll find different vector related methods in this class.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Point object. If you pass no parameters a Point is created set to (0, 0).
|
||||
*
|
||||
* @constructor
|
||||
* @param {number} [x=0] - The horizontal position of this Point.
|
||||
* @param {number} [y=0] - The vertical position of this Point.
|
||||
*/
|
||||
Phaser.Point = function (x, y) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
|
||||
/**
|
||||
* @property {number} x - The x value of the point.
|
||||
*/
|
||||
this.x = x;
|
||||
|
||||
/**
|
||||
* @property {number} y - The y value of the point.
|
||||
*/
|
||||
this.y = y;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Point.prototype = {
|
||||
|
||||
/**
|
||||
* Copies the x and y properties from any given object to this Point.
|
||||
*
|
||||
* @method Phaser.Point#copyFrom
|
||||
* @param {any} source - The object to copy from.
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
copyFrom: function (source) {
|
||||
|
||||
return this.setTo(source.x, source.y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Inverts the x and y values of this Point
|
||||
*
|
||||
* @method Phaser.Point#invert
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
invert: function () {
|
||||
|
||||
return this.setTo(this.y, this.x);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the `x` and `y` values of this Point object to the given values.
|
||||
* If you omit the `y` value then the `x` value will be applied to both, for example:
|
||||
* `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
|
||||
*
|
||||
* @method Phaser.Point#setTo
|
||||
* @param {number} x - The horizontal value of this point.
|
||||
* @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
setTo: function (x, y) {
|
||||
|
||||
this.x = x || 0;
|
||||
this.y = y || ( (y !== 0) ? this.x : 0 );
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the `x` and `y` values of this Point object to the given values.
|
||||
* If you omit the `y` value then the `x` value will be applied to both, for example:
|
||||
* `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
|
||||
*
|
||||
* @method Phaser.Point#set
|
||||
* @param {number} x - The horizontal value of this point.
|
||||
* @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
set: function (x, y) {
|
||||
|
||||
this.x = x || 0;
|
||||
this.y = y || ( (y !== 0) ? this.x : 0 );
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds the given x and y values to this Point.
|
||||
*
|
||||
* @method Phaser.Point#add
|
||||
* @param {number} x - The value to add to Point.x.
|
||||
* @param {number} y - The value to add to Point.y.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
add: function (x, y) {
|
||||
|
||||
this.x += x;
|
||||
this.y += y;
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Subtracts the given x and y values from this Point.
|
||||
*
|
||||
* @method Phaser.Point#subtract
|
||||
* @param {number} x - The value to subtract from Point.x.
|
||||
* @param {number} y - The value to subtract from Point.y.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
subtract: function (x, y) {
|
||||
|
||||
this.x -= x;
|
||||
this.y -= y;
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`.
|
||||
*
|
||||
* @method Phaser.Point#multiply
|
||||
* @param {number} x - The value to multiply Point.x by.
|
||||
* @param {number} y - The value to multiply Point.x by.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
multiply: function (x, y) {
|
||||
|
||||
this.x *= x;
|
||||
this.y *= y;
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Divides Point.x and Point.y by the given x and y values.
|
||||
*
|
||||
* @method Phaser.Point#divide
|
||||
* @param {number} x - The value to divide Point.x by.
|
||||
* @param {number} y - The value to divide Point.x by.
|
||||
* @return {Phaser.Point} This Point object. Useful for chaining method calls.
|
||||
*/
|
||||
divide: function (x, y) {
|
||||
|
||||
this.x /= x;
|
||||
this.y /= y;
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clamps the x value of this Point to be between the given min and max.
|
||||
*
|
||||
* @method Phaser.Point#clampX
|
||||
* @param {number} min - The minimum value to clamp this Point to.
|
||||
* @param {number} max - The maximum value to clamp this Point to.
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
clampX: function (min, max) {
|
||||
|
||||
this.x = Phaser.Math.clamp(this.x, min, max);
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clamps the y value of this Point to be between the given min and max
|
||||
*
|
||||
* @method Phaser.Point#clampY
|
||||
* @param {number} min - The minimum value to clamp this Point to.
|
||||
* @param {number} max - The maximum value to clamp this Point to.
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
clampY: function (min, max) {
|
||||
|
||||
this.y = Phaser.Math.clamp(this.y, min, max);
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clamps this Point object values to be between the given min and max.
|
||||
*
|
||||
* @method Phaser.Point#clamp
|
||||
* @param {number} min - The minimum value to clamp this Point to.
|
||||
* @param {number} max - The maximum value to clamp this Point to.
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
clamp: function (min, max) {
|
||||
|
||||
this.x = Phaser.Math.clamp(this.x, min, max);
|
||||
this.y = Phaser.Math.clamp(this.y, min, max);
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a copy of the given Point.
|
||||
*
|
||||
* @method Phaser.Point#clone
|
||||
* @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
clone: function (output) {
|
||||
|
||||
if (typeof output === "undefined")
|
||||
{
|
||||
output = new Phaser.Point(this.x, this.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
output.setTo(this.x, this.y);
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x and y properties from this Point to any given object.
|
||||
*
|
||||
* @method Phaser.Point#copyTo
|
||||
* @param {any} dest - The object to copy to.
|
||||
* @return {Object} The dest object.
|
||||
*/
|
||||
copyTo: function (dest) {
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
|
||||
return dest;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
|
||||
*
|
||||
* @method Phaser.Point#distance
|
||||
* @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
|
||||
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
|
||||
* @return {number} The distance between this Point object and the destination Point object.
|
||||
*/
|
||||
distance: function (dest, round) {
|
||||
|
||||
return Phaser.Point.distance(this, dest, round);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the given objects x/y values are equal to this Point object.
|
||||
*
|
||||
* @method Phaser.Point#equals
|
||||
* @param {Phaser.Point|any} a - The object to compare with this Point.
|
||||
* @return {boolean} A value of true if the x and y points are equal, otherwise false.
|
||||
*/
|
||||
equals: function (a) {
|
||||
|
||||
return (a.x === this.x && a.y === this.y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the angle between this Point object and another object with public x and y properties.
|
||||
*
|
||||
* @method Phaser.Point#angle
|
||||
* @param {Phaser.Point|any} a - The object to get the angle from this Point to.
|
||||
* @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
|
||||
* @return {number} The angle between the two objects.
|
||||
*/
|
||||
angle: function (a, asDegrees) {
|
||||
|
||||
if (typeof asDegrees === 'undefined') { asDegrees = false; }
|
||||
|
||||
if (asDegrees)
|
||||
{
|
||||
return Phaser.Math.radToDeg(Math.atan2(a.y - this.y, a.x - this.x));
|
||||
}
|
||||
else
|
||||
{
|
||||
return Math.atan2(a.y - this.y, a.x - this.x);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the angle squared between this Point object and another object with public x and y properties.
|
||||
*
|
||||
* @method Phaser.Point#angleSq
|
||||
* @param {Phaser.Point|any} a - The object to get the angleSq from this Point to.
|
||||
* @return {number} The angleSq between the two objects.
|
||||
*/
|
||||
angleSq: function (a) {
|
||||
|
||||
return this.subtract(a).angle(a.subtract(this));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Rotates this Point around the x/y coordinates given to the desired angle.
|
||||
*
|
||||
* @method Phaser.Point#rotate
|
||||
* @param {number} x - The x coordinate of the anchor point.
|
||||
* @param {number} y - The y coordinate of the anchor point.
|
||||
* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
|
||||
* @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)?
|
||||
* @param {number} [distance] - An optional distance constraint between the Point and the anchor.
|
||||
* @return {Phaser.Point} The modified point object.
|
||||
*/
|
||||
rotate: function (x, y, angle, asDegrees, distance) {
|
||||
|
||||
return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Calculates the length of the Point object.
|
||||
*
|
||||
* @method Phaser.Point#getMagnitude
|
||||
* @return {number} The length of the Point.
|
||||
*/
|
||||
getMagnitude: function () {
|
||||
|
||||
return Math.sqrt((this.x * this.x) + (this.y * this.y));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Calculates the length squared of the Point object.
|
||||
*
|
||||
* @method Phaser.Point#getMagnitudeSq
|
||||
* @return {number} The length ^ 2 of the Point.
|
||||
*/
|
||||
getMagnitudeSq: function () {
|
||||
|
||||
return (this.x * this.x) + (this.y * this.y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Alters the length of the Point without changing the direction.
|
||||
*
|
||||
* @method Phaser.Point#setMagnitude
|
||||
* @param {number} magnitude - The desired magnitude of the resulting Point.
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
setMagnitude: function (magnitude) {
|
||||
|
||||
return this.normalize().multiply(magnitude, magnitude);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Alters the Point object so that its length is 1, but it retains the same direction.
|
||||
*
|
||||
* @method Phaser.Point#normalize
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
normalize: function () {
|
||||
|
||||
if (!this.isZero())
|
||||
{
|
||||
var m = this.getMagnitude();
|
||||
this.x /= m;
|
||||
this.y /= m;
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determine if this point is at 0,0.
|
||||
*
|
||||
* @method Phaser.Point#isZero
|
||||
* @return {boolean} True if this Point is 0,0, otherwise false.
|
||||
*/
|
||||
isZero: function () {
|
||||
|
||||
return (this.x === 0 && this.y === 0);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The dot product of this and another Point object.
|
||||
*
|
||||
* @method Phaser.Point#dot
|
||||
* @param {Phaser.Point} a - The Point object to get the dot product combined with this Point.
|
||||
* @return {number} The result.
|
||||
*/
|
||||
dot: function (a) {
|
||||
|
||||
return ((this.x * a.x) + (this.y * a.y));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The cross product of this and another Point object.
|
||||
*
|
||||
* @method Phaser.Point#cross
|
||||
* @param {Phaser.Point} a - The Point object to get the cross product combined with this Point.
|
||||
* @return {number} The result.
|
||||
*/
|
||||
cross: function (a) {
|
||||
|
||||
return ((this.x * a.y) - (this.y * a.x));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Make this Point perpendicular (90 degrees rotation)
|
||||
*
|
||||
* @method Phaser.Point#perp
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
perp: function () {
|
||||
|
||||
return this.setTo(-this.y, this.x);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Make this Point perpendicular (-90 degrees rotation)
|
||||
*
|
||||
* @method Phaser.Point#rperp
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
rperp: function () {
|
||||
|
||||
return this.setTo(this.y, -this.x);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Right-hand normalize (make unit length) this Point.
|
||||
*
|
||||
* @method Phaser.Point#normalRightHand
|
||||
* @return {Phaser.Point} This Point object.
|
||||
*/
|
||||
normalRightHand: function () {
|
||||
|
||||
return this.setTo(this.y * -1, this.x);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object.
|
||||
*
|
||||
* @method Phaser.Point#toString
|
||||
* @return {string} A string representation of the instance.
|
||||
*/
|
||||
toString: function () {
|
||||
|
||||
return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Point.prototype.constructor = Phaser.Point;
|
||||
|
||||
/**
|
||||
* Adds the coordinates of two points together to create a new point.
|
||||
*
|
||||
* @method Phaser.Point.add
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.add = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
out.x = a.x + b.x;
|
||||
out.y = a.y + b.y;
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Subtracts the coordinates of two points to create a new point.
|
||||
*
|
||||
* @method Phaser.Point.subtract
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.subtract = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
out.x = a.x - b.x;
|
||||
out.y = a.y - b.y;
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Multiplies the coordinates of two points to create a new point.
|
||||
*
|
||||
* @method Phaser.Point.multiply
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.multiply = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
out.x = a.x * b.x;
|
||||
out.y = a.y * b.y;
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Divides the coordinates of two points to create a new point.
|
||||
*
|
||||
* @method Phaser.Point.divide
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.divide = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
out.x = a.x / b.x;
|
||||
out.y = a.y / b.y;
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
|
||||
*
|
||||
* @method Phaser.Point.equals
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @return {boolean} A value of true if the Points are equal, otherwise false.
|
||||
*/
|
||||
Phaser.Point.equals = function (a, b) {
|
||||
|
||||
return (a.x === b.x && a.y === b.y);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the angle between two Point objects.
|
||||
*
|
||||
* @method Phaser.Point.angle
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @return {number} The angle between the two Points.
|
||||
*/
|
||||
Phaser.Point.angle = function (a, b) {
|
||||
|
||||
// return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
|
||||
return Math.atan2(a.y - b.y, a.x - b.x);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the angle squared between two Point objects.
|
||||
*
|
||||
* @method Phaser.Point.angleSq
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @return {number} The angle squared between the two Points.
|
||||
*/
|
||||
Phaser.Point.angleSq = function (a, b) {
|
||||
|
||||
return a.subtract(b).angle(b.subtract(a));
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a negative Point.
|
||||
*
|
||||
* @method Phaser.Point.negative
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.negative = function (a, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(-a.x, -a.y);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds two 2D Points together and multiplies the result by the given scalar.
|
||||
*
|
||||
* @method Phaser.Point.multiplyAdd
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {number} s - The scaling value.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.multiplyAdd = function (a, b, s, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(a.x + b.x * s, a.y + b.y * s);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point.
|
||||
*
|
||||
* @method Phaser.Point.interpolate
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.interpolate = function (a, b, f, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a perpendicular vector (90 degrees rotation)
|
||||
*
|
||||
* @method Phaser.Point.perp
|
||||
* @param {Phaser.Point} a - The Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.perp = function (a, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(-a.y, a.x);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a perpendicular vector (-90 degrees rotation)
|
||||
*
|
||||
* @method Phaser.Point.rperp
|
||||
* @param {Phaser.Point} a - The Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.rperp = function (a, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(a.y, -a.x);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
|
||||
*
|
||||
* @method Phaser.Point.distance
|
||||
* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
|
||||
* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
|
||||
* @param {boolean} [round] - Round the distance to the nearest integer (default false).
|
||||
* @return {number} The distance between this Point object and the destination Point object.
|
||||
*/
|
||||
Phaser.Point.distance = function (a, b, round) {
|
||||
|
||||
if (typeof round === "undefined") { round = false; }
|
||||
|
||||
if (round)
|
||||
{
|
||||
return Phaser.Math.distanceRounded(a.x, a.y, b.x, b.y);
|
||||
}
|
||||
else
|
||||
{
|
||||
return Phaser.Math.distance(a.x, a.y, b.x, b.y);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Project two Points onto another Point.
|
||||
*
|
||||
* @method Phaser.Point.project
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.project = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
var amt = a.dot(b) / b.getMagnitudeSq();
|
||||
|
||||
if (amt !== 0)
|
||||
{
|
||||
out.setTo(amt * b.x, amt * b.y);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Project two Points onto a Point of unit length.
|
||||
*
|
||||
* @method Phaser.Point.projectUnit
|
||||
* @param {Phaser.Point} a - The first Point object.
|
||||
* @param {Phaser.Point} b - The second Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.projectUnit = function (a, b, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
var amt = a.dot(b);
|
||||
|
||||
if (amt !== 0)
|
||||
{
|
||||
out.setTo(amt * b.x, amt * b.y);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Right-hand normalize (make unit length) a Point.
|
||||
*
|
||||
* @method Phaser.Point.normalRightHand
|
||||
* @param {Phaser.Point} a - The Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.normalRightHand = function (a, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
return out.setTo(a.y * -1, a.x);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize (make unit length) a Point.
|
||||
*
|
||||
* @method Phaser.Point.normalize
|
||||
* @param {Phaser.Point} a - The Point object.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.normalize = function (a, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
var m = a.getMagnitude();
|
||||
|
||||
if (m !== 0)
|
||||
{
|
||||
out.setTo(a.x / m, a.y / m);
|
||||
}
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Rotates a Point around the x/y coordinates given to the desired angle.
|
||||
*
|
||||
* @method Phaser.Point.rotate
|
||||
* @param {Phaser.Point} a - The Point object to rotate.
|
||||
* @param {number} x - The x coordinate of the anchor point
|
||||
* @param {number} y - The y coordinate of the anchor point
|
||||
* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
|
||||
* @param {boolean} [asDegrees=false] - Is the given rotation in radians (false) or degrees (true)?
|
||||
* @param {number} [distance] - An optional distance constraint between the Point and the anchor.
|
||||
* @return {Phaser.Point} The modified point object.
|
||||
*/
|
||||
Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
|
||||
|
||||
asDegrees = asDegrees || false;
|
||||
distance = distance || null;
|
||||
|
||||
if (asDegrees)
|
||||
{
|
||||
angle = Phaser.Math.degToRad(angle);
|
||||
}
|
||||
|
||||
// Get distance from origin (cx/cy) to this point
|
||||
if (distance === null)
|
||||
{
|
||||
distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y)));
|
||||
}
|
||||
|
||||
return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
|
||||
*
|
||||
* @method Phaser.Point.centroid
|
||||
* @param {Phaser.Point[]} points - The array of one or more points.
|
||||
* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
|
||||
* @return {Phaser.Point} The new Point object.
|
||||
*/
|
||||
Phaser.Point.centroid = function (points, out) {
|
||||
|
||||
if (typeof out === "undefined") { out = new Phaser.Point(); }
|
||||
|
||||
if (Object.prototype.toString.call(points) !== '[object Array]')
|
||||
{
|
||||
throw new Error("Phaser.Point. Parameter 'points' must be an array");
|
||||
}
|
||||
|
||||
var pointslength = points.length;
|
||||
|
||||
if (pointslength < 1)
|
||||
{
|
||||
throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
|
||||
}
|
||||
|
||||
if (pointslength === 1)
|
||||
{
|
||||
out.copyFrom(points[0]);
|
||||
return out;
|
||||
}
|
||||
|
||||
for (var i = 0; i < pointslength; i++)
|
||||
{
|
||||
Phaser.Point.add(out, points[i], out);
|
||||
}
|
||||
|
||||
out.divide(pointslength, pointslength);
|
||||
|
||||
return out;
|
||||
|
||||
};
|
||||
|
||||
// Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
|
||||
PIXI.Point = Phaser.Point;
|
||||
200
src/geom/Polygon.js
Normal file
200
src/geom/Polygon.js
Normal file
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @author Adrien Brault <adrien.brault@gmail.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new Polygon. You have to provide a list of points.
|
||||
* This can be an array of Points that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...],
|
||||
* or the arguments passed can be all the points of the polygon e.g. `new Phaser.Polygon(new Phaser.Point(), new Phaser.Point(), ...)`, or the
|
||||
* arguments passed can be flat x,y values e.g. `new Phaser.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
|
||||
*
|
||||
* @class Phaser.Polygon
|
||||
* @classdesc The polygon represents a list of orderded points in space
|
||||
* @constructor
|
||||
* @param {Array<Phaser.Point>|Array<number>} points - The array of Points.
|
||||
*/
|
||||
Phaser.Polygon = function (points) {
|
||||
|
||||
/**
|
||||
* @property {number} type - The base object type.
|
||||
*/
|
||||
this.type = Phaser.POLYGON;
|
||||
|
||||
//if points isn't an array, use arguments as the array
|
||||
if (!(points instanceof Array))
|
||||
{
|
||||
points = Array.prototype.slice.call(arguments);
|
||||
}
|
||||
|
||||
//if this is a flat array of numbers, convert it to points
|
||||
if (typeof points[0] === 'number')
|
||||
{
|
||||
var p = [];
|
||||
|
||||
for (var i = 0, len = points.length; i < len; i += 2)
|
||||
{
|
||||
p.push(new Phaser.Point(points[i], points[i + 1]));
|
||||
}
|
||||
|
||||
points = p;
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {array<Phaser.Point>|array<number>} points - The array of vertex Points.
|
||||
* @private
|
||||
*/
|
||||
this._points = points;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Polygon.prototype = {
|
||||
|
||||
/**
|
||||
* Creates a clone of this polygon.
|
||||
*
|
||||
* @method Phaser.Polygon#clone
|
||||
* @return {Phaser.Polygon} A copy of the polygon.
|
||||
*/
|
||||
clone: function () {
|
||||
|
||||
var points = [];
|
||||
|
||||
for (var i=0; i < this.points.length; i++)
|
||||
{
|
||||
points.push(this.points[i].clone());
|
||||
}
|
||||
|
||||
return new Phaser.Polygon(points);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks whether the x and y coordinates are contained within this polygon.
|
||||
*
|
||||
* @method Phaser.Polygon#contains
|
||||
* @param {number} x - The X value of the coordinate to test.
|
||||
* @param {number} y - The Y value of the coordinate to test.
|
||||
* @return {boolean} True if the coordinates are within this polygon, otherwise false.
|
||||
*/
|
||||
contains: function (x, y) {
|
||||
|
||||
var inside = false;
|
||||
|
||||
// use some raycasting to test hits https://github.com/substack/point-in-polygon/blob/master/index.js
|
||||
for (var i = 0, j = this.points.length - 1; i < this.points.length; j = i++)
|
||||
{
|
||||
var xi = this.points[i].x;
|
||||
var yi = this.points[i].y;
|
||||
var xj = this.points[j].x;
|
||||
var yj = this.points[j].y;
|
||||
|
||||
var intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
|
||||
|
||||
if (intersect)
|
||||
{
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
|
||||
return inside;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Polygon.prototype.constructor = Phaser.Polygon;
|
||||
|
||||
/*
|
||||
* Sets and modifies the points of this polygon.
|
||||
*
|
||||
* @name Phaser.Polygon#points
|
||||
* @property {array<Phaser.Point>|array<number>} points - The array of vertex points
|
||||
*/
|
||||
Object.defineProperty(Phaser.Polygon.prototype, 'points', {
|
||||
|
||||
get: function() {
|
||||
return this._points;
|
||||
},
|
||||
|
||||
set: function(points) {
|
||||
|
||||
//if points isn't an array, use arguments as the array
|
||||
if (!(points instanceof Array))
|
||||
{
|
||||
points = Array.prototype.slice.call(arguments);
|
||||
}
|
||||
|
||||
//if this is a flat array of numbers, convert it to points
|
||||
if (typeof points[0] === 'number')
|
||||
{
|
||||
var p = [];
|
||||
|
||||
for (var i = 0, len = points.length; i < len; i += 2)
|
||||
{
|
||||
p.push(new Phaser.Point(points[i], points[i + 1]));
|
||||
}
|
||||
|
||||
points = p;
|
||||
}
|
||||
|
||||
this._points = points;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Returns the area of the polygon.
|
||||
*
|
||||
* @name Phaser.Circle#right
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Polygon.prototype, 'area', {
|
||||
|
||||
get: function() {
|
||||
|
||||
var p1;
|
||||
var p2;
|
||||
var avgHeight;
|
||||
var width;
|
||||
var i;
|
||||
var y0 = Number.MAX_VALUE;
|
||||
var area = 0;
|
||||
|
||||
// Find lowest boundary
|
||||
for (i = 0; i < this.points.length; i++)
|
||||
{
|
||||
if (this.points[i].y < y0)
|
||||
{
|
||||
y0 = this.points[i].y;
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i< this.points.length; i++)
|
||||
{
|
||||
p1 = this.points[i];
|
||||
|
||||
if (i === this.points.length - 1)
|
||||
{
|
||||
p2 = this.points[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
p2 = this.points[i+1];
|
||||
}
|
||||
|
||||
avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2;
|
||||
width = p1.x - p2.x;
|
||||
area += avgHeight * width;
|
||||
}
|
||||
|
||||
return area;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
// Because PIXI uses its own Polygon, we'll replace it with ours to avoid duplicating code or confusion.
|
||||
PIXI.Polygon = Phaser.Polygon;
|
||||
775
src/geom/Rectangle.js
Normal file
775
src/geom/Rectangle.js
Normal file
@@ -0,0 +1,775 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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 Phaser.Rectangle
|
||||
* @constructor
|
||||
* @param {number} x - The x coordinate of the top-left corner of the Rectangle.
|
||||
* @param {number} y - The y coordinate of the top-left corner of the Rectangle.
|
||||
* @param {number} width - The width of the Rectangle.
|
||||
* @param {number} height - The height of the Rectangle.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
Phaser.Rectangle = function (x, y, width, height) {
|
||||
|
||||
x = x || 0;
|
||||
y = y || 0;
|
||||
width = width || 0;
|
||||
height = height || 0;
|
||||
|
||||
/**
|
||||
* @property {number} x - The x coordinate of the top-left corner of the Rectangle.
|
||||
*/
|
||||
this.x = x;
|
||||
|
||||
/**
|
||||
* @property {number} y - The y coordinate of the top-left corner of the Rectangle.
|
||||
*/
|
||||
this.y = y;
|
||||
|
||||
/**
|
||||
* @property {number} width - The width of the Rectangle.
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - The height of the Rectangle.
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Rectangle.prototype = {
|
||||
|
||||
/**
|
||||
* Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
|
||||
* @method Phaser.Rectangle#offset
|
||||
* @param {number} dx - Moves the x value of the Rectangle object by this amount.
|
||||
* @param {number} dy - Moves the y value of the Rectangle object by this amount.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
offset: function (dx, dy) {
|
||||
|
||||
this.x += dx;
|
||||
this.y += dy;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
|
||||
* @method Phaser.Rectangle#offsetPoint
|
||||
* @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
offsetPoint: function (point) {
|
||||
|
||||
return this.offset(point.x, point.y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the members of Rectangle to the specified values.
|
||||
* @method Phaser.Rectangle#setTo
|
||||
* @param {number} x - The x coordinate of the top-left corner of the Rectangle.
|
||||
* @param {number} y - The y coordinate of the top-left corner of the Rectangle.
|
||||
* @param {number} width - The width of the Rectangle in pixels.
|
||||
* @param {number} height - The height of the Rectangle in pixels.
|
||||
* @return {Phaser.Rectangle} This Rectangle object
|
||||
*/
|
||||
setTo: function (x, y, width, height) {
|
||||
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Runs Math.floor() on both the x and y values of this Rectangle.
|
||||
* @method Phaser.Rectangle#floor
|
||||
*/
|
||||
floor: function () {
|
||||
|
||||
this.x = Math.floor(this.x);
|
||||
this.y = Math.floor(this.y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Runs Math.floor() on the x, y, width and height values of this Rectangle.
|
||||
* @method Phaser.Rectangle#floorAll
|
||||
*/
|
||||
floorAll: function () {
|
||||
|
||||
this.x = Math.floor(this.x);
|
||||
this.y = Math.floor(this.y);
|
||||
this.width = Math.floor(this.width);
|
||||
this.height = Math.floor(this.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y, width and height properties from any given object to this Rectangle.
|
||||
* @method Phaser.Rectangle#copyFrom
|
||||
* @param {any} source - The object to copy from.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
copyFrom: function (source) {
|
||||
|
||||
return this.setTo(source.x, source.y, source.width, source.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Copies the x, y, width and height properties from this Rectangle to any given object.
|
||||
* @method Phaser.Rectangle#copyTo
|
||||
* @param {any} source - The object to copy to.
|
||||
* @return {object} This object.
|
||||
*/
|
||||
copyTo: function (dest) {
|
||||
|
||||
dest.x = this.x;
|
||||
dest.y = this.y;
|
||||
dest.width = this.width;
|
||||
dest.height = this.height;
|
||||
|
||||
return dest;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
|
||||
* @method Phaser.Rectangle#inflate
|
||||
* @param {number} dx - The amount to be added to the left side of the Rectangle.
|
||||
* @param {number} dy - The amount to be added to the bottom side of the Rectangle.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
inflate: function (dx, dy) {
|
||||
|
||||
return Phaser.Rectangle.inflate(this, dx, dy);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
|
||||
* @method Phaser.Rectangle#size
|
||||
* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
|
||||
* @return {Phaser.Point} The size of the Rectangle object.
|
||||
*/
|
||||
size: function (output) {
|
||||
|
||||
return Phaser.Rectangle.size(this, output);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
|
||||
* @method Phaser.Rectangle#clone
|
||||
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle}
|
||||
*/
|
||||
clone: function (output) {
|
||||
|
||||
return Phaser.Rectangle.clone(this, output);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
|
||||
* @method Phaser.Rectangle#contains
|
||||
* @param {number} x - The x coordinate of the point to test.
|
||||
* @param {number} y - The y coordinate of the point to test.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
contains: function (x, y) {
|
||||
|
||||
return Phaser.Rectangle.contains(this, x, y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the first Rectangle object is fully contained within the second Rectangle object.
|
||||
* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
|
||||
* @method Phaser.Rectangle#containsRect
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
containsRect: function (b) {
|
||||
|
||||
return Phaser.Rectangle.containsRect(this, b);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the two Rectangles are equal.
|
||||
* This method compares the x, y, width and height properties of each Rectangle.
|
||||
* @method Phaser.Rectangle#equals
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
|
||||
*/
|
||||
equals: function (b) {
|
||||
|
||||
return Phaser.Rectangle.equals(this, b);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
|
||||
* @method Phaser.Rectangle#intersection
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
|
||||
*/
|
||||
intersection: function (b, out) {
|
||||
|
||||
return Phaser.Rectangle.intersection(this, b, out);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the two Rectangles intersect with each other.
|
||||
* This method checks the x, y, width, and height properties of the Rectangles.
|
||||
* @method Phaser.Rectangle#intersects
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0.
|
||||
* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
|
||||
*/
|
||||
intersects: function (b, tolerance) {
|
||||
|
||||
return Phaser.Rectangle.intersects(this, b, tolerance);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determines whether the object specified intersects (overlaps) with the given values.
|
||||
* @method Phaser.Rectangle#intersectsRaw
|
||||
* @param {number} left - Description.
|
||||
* @param {number} right - Description.
|
||||
* @param {number} top - Description.
|
||||
* @param {number} bottomt - Description.
|
||||
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
|
||||
* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
|
||||
*/
|
||||
intersectsRaw: function (left, right, top, bottom, tolerance) {
|
||||
|
||||
return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
|
||||
* @method Phaser.Rectangle#union
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
|
||||
*/
|
||||
union: function (b, out) {
|
||||
|
||||
return Phaser.Rectangle.union(this, b, out);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a string representation of this object.
|
||||
* @method Phaser.Rectangle#toString
|
||||
* @return {string} A string representation of the instance.
|
||||
*/
|
||||
toString: function () {
|
||||
|
||||
return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Rectangle#halfWidth
|
||||
* @property {number} halfWidth - Half of the width of the Rectangle.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
|
||||
|
||||
get: function () {
|
||||
return Math.round(this.width / 2);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Rectangle#halfHeight
|
||||
* @property {number} halfHeight - Half of the height of the Rectangle.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
|
||||
|
||||
get: function () {
|
||||
return Math.round(this.height / 2);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
|
||||
* @name Phaser.Rectangle#bottom
|
||||
* @property {number} bottom - The sum of the y and height properties.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.y + this.height;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
if (value <= this.y) {
|
||||
this.height = 0;
|
||||
} else {
|
||||
this.height = (this.y - value);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The location of the Rectangles bottom right corner as a Point object.
|
||||
* @name Phaser.Rectangle#bottom
|
||||
* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
|
||||
|
||||
get: function () {
|
||||
return new Phaser.Point(this.right, this.bottom);
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.right = value.x;
|
||||
this.bottom = value.y;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property.
|
||||
* @name Phaser.Rectangle#left
|
||||
* @property {number} left - The x coordinate of the left of the Rectangle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "left", {
|
||||
|
||||
get: function () {
|
||||
return this.x;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
if (value >= this.right) {
|
||||
this.width = 0;
|
||||
} else {
|
||||
this.width = this.right - value;
|
||||
}
|
||||
this.x = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property.
|
||||
* @name Phaser.Rectangle#right
|
||||
* @property {number} right - The sum of the x and width properties.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.x + this.width;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
if (value <= this.x) {
|
||||
this.width = 0;
|
||||
} else {
|
||||
this.width = this.x + value;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The volume of the Rectangle derived from width * height.
|
||||
* @name Phaser.Rectangle#volume
|
||||
* @property {number} volume - The volume of the Rectangle derived from width * height.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
|
||||
|
||||
get: function () {
|
||||
return this.width * this.height;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The perimeter size of the Rectangle. This is the sum of all 4 sides.
|
||||
* @name Phaser.Rectangle#perimeter
|
||||
* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
|
||||
|
||||
get: function () {
|
||||
return (this.width * 2) + (this.height * 2);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The x coordinate of the center of the Rectangle.
|
||||
* @name Phaser.Rectangle#centerX
|
||||
* @property {number} centerX - The x coordinate of the center of the Rectangle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
|
||||
|
||||
get: function () {
|
||||
return this.x + this.halfWidth;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.x = value - this.halfWidth;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The y coordinate of the center of the Rectangle.
|
||||
* @name Phaser.Rectangle#centerY
|
||||
* @property {number} centerY - The y coordinate of the center of the Rectangle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
|
||||
|
||||
get: function () {
|
||||
return this.y + this.halfHeight;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.y = value - this.halfHeight;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties.
|
||||
* However it does affect the height property, whereas changing the y value does not affect the height property.
|
||||
* @name Phaser.Rectangle#top
|
||||
* @property {number} top - The y coordinate of the top of the Rectangle.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "top", {
|
||||
|
||||
get: function () {
|
||||
return this.y;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
if (value >= this.bottom) {
|
||||
this.height = 0;
|
||||
this.y = value;
|
||||
} else {
|
||||
this.height = (this.bottom - value);
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* The location of the Rectangles top left corner as a Point object.
|
||||
* @name Phaser.Rectangle#topLeft
|
||||
* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
|
||||
|
||||
get: function () {
|
||||
return new Phaser.Point(this.x, this.y);
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.x = value.x;
|
||||
this.y = value.y;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0.
|
||||
* If set to true then all of the Rectangle properties are set to 0.
|
||||
* @name Phaser.Rectangle#empty
|
||||
* @property {boolean} empty - Gets or sets the Rectangles empty state.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
|
||||
|
||||
get: function () {
|
||||
return (!this.width || !this.height);
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
if (value === true)
|
||||
{
|
||||
this.setTo(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
|
||||
|
||||
/**
|
||||
* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
|
||||
* @method Phaser.Rectangle.inflate
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {number} dx - The amount to be added to the left side of the Rectangle.
|
||||
* @param {number} dy - The amount to be added to the bottom side of the Rectangle.
|
||||
* @return {Phaser.Rectangle} This Rectangle object.
|
||||
*/
|
||||
Phaser.Rectangle.inflate = function (a, dx, dy) {
|
||||
|
||||
a.x -= dx;
|
||||
a.width += 2 * dx;
|
||||
a.y -= dy;
|
||||
a.height += 2 * dy;
|
||||
|
||||
return a;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
|
||||
* @method Phaser.Rectangle.inflatePoint
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
|
||||
* @return {Phaser.Rectangle} The Rectangle object.
|
||||
*/
|
||||
Phaser.Rectangle.inflatePoint = function (a, point) {
|
||||
|
||||
return Phaser.Rectangle.inflate(a, point.x, point.y);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
|
||||
* @method Phaser.Rectangle.size
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
|
||||
* @return {Phaser.Point} The size of the Rectangle object
|
||||
*/
|
||||
Phaser.Rectangle.size = function (a, output) {
|
||||
|
||||
if (typeof output === "undefined")
|
||||
{
|
||||
output = new Phaser.Point(a.width, a.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
output.setTo(a.width, a.height);
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
|
||||
* @method Phaser.Rectangle.clone
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle}
|
||||
*/
|
||||
Phaser.Rectangle.clone = function (a, output) {
|
||||
|
||||
if (typeof output === "undefined")
|
||||
{
|
||||
output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
output.setTo(a.x, a.y, a.width, a.height);
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
|
||||
* @method Phaser.Rectangle.contains
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {number} x - The x coordinate of the point to test.
|
||||
* @param {number} y - The y coordinate of the point to test.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.contains = function (a, x, y) {
|
||||
|
||||
if (a.width <= 0 || a.height <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the specified coordinates are contained within the region defined by the given raw values.
|
||||
* @method Phaser.Rectangle.containsRaw
|
||||
* @param {number} rx - The x coordinate of the top left of the area.
|
||||
* @param {number} ry - The y coordinate of the top left of the area.
|
||||
* @param {number} rw - The width of the area.
|
||||
* @param {number} rh - The height of the area.
|
||||
* @param {number} x - The x coordinate of the point to test.
|
||||
* @param {number} y - The y coordinate of the point to test.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
|
||||
|
||||
return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh));
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
|
||||
* @method Phaser.Rectangle.containsPoint
|
||||
* @param {Phaser.Rectangle} a - The Rectangle object.
|
||||
* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.containsPoint = function (a, point) {
|
||||
|
||||
return Phaser.Rectangle.contains(a, point.x, point.y);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the first Rectangle object is fully contained within the second Rectangle object.
|
||||
* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
|
||||
* @method Phaser.Rectangle.containsRect
|
||||
* @param {Phaser.Rectangle} a - The first Rectangle object.
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.containsRect = function (a, b) {
|
||||
|
||||
// If the given rect has a larger volume than this one then it can never contain it
|
||||
if (a.volume > b.volume)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the two Rectangles are equal.
|
||||
* This method compares the x, y, width and height properties of each Rectangle.
|
||||
* @method Phaser.Rectangle.equals
|
||||
* @param {Phaser.Rectangle} a - The first Rectangle object.
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.equals = function (a, b) {
|
||||
|
||||
return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
|
||||
* @method Phaser.Rectangle.intersection
|
||||
* @param {Phaser.Rectangle} a - The first Rectangle object.
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
|
||||
*/
|
||||
Phaser.Rectangle.intersection = function (a, b, output) {
|
||||
|
||||
if (typeof output === "undefined")
|
||||
{
|
||||
output = new Phaser.Rectangle();
|
||||
}
|
||||
|
||||
if (Phaser.Rectangle.intersects(a, b))
|
||||
{
|
||||
output.x = Math.max(a.x, b.x);
|
||||
output.y = Math.max(a.y, b.y);
|
||||
output.width = Math.min(a.right, b.right) - output.x;
|
||||
output.height = Math.min(a.bottom, b.bottom) - output.y;
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the two Rectangles intersect with each other.
|
||||
* This method checks the x, y, width, and height properties of the Rectangles.
|
||||
* @method Phaser.Rectangle.intersects
|
||||
* @param {Phaser.Rectangle} a - The first Rectangle object.
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.intersects = function (a, b) {
|
||||
|
||||
if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the object specified intersects (overlaps) with the given values.
|
||||
* @method Phaser.Rectangle.intersectsRaw
|
||||
* @param {number} left - Description.
|
||||
* @param {number} right - Description.
|
||||
* @param {number} top - Description.
|
||||
* @param {number} bottom - Description.
|
||||
* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
|
||||
* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
|
||||
*/
|
||||
Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
|
||||
|
||||
if (typeof tolerance === "undefined") { tolerance = 0; }
|
||||
|
||||
return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
|
||||
* @method Phaser.Rectangle.union
|
||||
* @param {Phaser.Rectangle} a - The first Rectangle object.
|
||||
* @param {Phaser.Rectangle} b - The second Rectangle object.
|
||||
* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
|
||||
* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
|
||||
*/
|
||||
Phaser.Rectangle.union = function (a, b, output) {
|
||||
|
||||
if (typeof output === "undefined")
|
||||
{
|
||||
output = new Phaser.Rectangle();
|
||||
}
|
||||
|
||||
return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top));
|
||||
|
||||
};
|
||||
|
||||
// Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
|
||||
PIXI.Rectangle = Phaser.Rectangle;
|
||||
PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
|
||||
584
src/input/Gamepad.js
Normal file
584
src/input/Gamepad.js
Normal file
@@ -0,0 +1,584 @@
|
||||
/**
|
||||
* @author @karlmacklin <tacklemcclean@gmail.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Gamepad class handles looking after gamepad input for your game.
|
||||
* Remember to call gamepad.start(); expecting input!
|
||||
*
|
||||
* HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
|
||||
* At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
|
||||
* via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
|
||||
* This class has constants for Windows 7 Chrome mapping of XBOX 360 controller.
|
||||
*
|
||||
* @class Phaser.Gamepad
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Gamepad = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
|
||||
* @private
|
||||
*/
|
||||
this._gamepads = [
|
||||
new Phaser.SinglePad(game, this),
|
||||
new Phaser.SinglePad(game, this),
|
||||
new Phaser.SinglePad(game, this),
|
||||
new Phaser.SinglePad(game, this)
|
||||
];
|
||||
|
||||
/**
|
||||
* @property {Object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
|
||||
* @private
|
||||
*/
|
||||
this._gamepadIndexMap = {};
|
||||
|
||||
/**
|
||||
* @property {Array} _rawPads - The raw state of the gamepads from the browser
|
||||
* @private
|
||||
*/
|
||||
this._rawPads = [];
|
||||
|
||||
/**
|
||||
* @property {boolean} _active - Private flag for whether or not the API is polled
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._active = false;
|
||||
|
||||
/**
|
||||
* You can disable all Gamepad Input by setting disabled to true. While true all new input related events will be ignored.
|
||||
* @property {boolean} disabled - The disabled state of the Gamepad.
|
||||
* @default
|
||||
*/
|
||||
this.disabled = false;
|
||||
|
||||
/**
|
||||
* Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation.
|
||||
* @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
|
||||
* @private
|
||||
*/
|
||||
this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') != -1) || !!navigator.getGamepads;
|
||||
|
||||
/**
|
||||
* Used to check for differences between earlier polls and current state of gamepads.
|
||||
* @property {Array} _prevRawGamepadTypes
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._prevRawGamepadTypes = [];
|
||||
|
||||
/**
|
||||
* Used to check for differences between earlier polls and current state of gamepads.
|
||||
* @property {Array} _prevTimestamps
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._prevTimestamps = [];
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which the callbacks are run.
|
||||
*/
|
||||
this.callbackContext = this;
|
||||
|
||||
/**
|
||||
* @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
|
||||
*/
|
||||
this.onConnectCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
|
||||
*/
|
||||
this.onDisconnectCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
|
||||
*/
|
||||
this.onDownCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
|
||||
*/
|
||||
this.onUpCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
|
||||
*/
|
||||
this.onAxisCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
|
||||
*/
|
||||
this.onFloatCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
|
||||
* @private
|
||||
*/
|
||||
this._ongamepadconnected = null;
|
||||
|
||||
/**
|
||||
* @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
|
||||
* @private
|
||||
*/
|
||||
this._gamepaddisconnected = null;
|
||||
};
|
||||
|
||||
Phaser.Gamepad.prototype = {
|
||||
|
||||
/**
|
||||
* Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons
|
||||
* @method Phaser.Gamepad#addCallbacks
|
||||
* @param {Object} context - The context under which the callbacks are run.
|
||||
* @param {Object} callbacks - Object that takes six different callback methods:
|
||||
* onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
|
||||
*/
|
||||
addCallbacks: function (context, callbacks) {
|
||||
|
||||
if (typeof callbacks !== 'undefined')
|
||||
{
|
||||
this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
|
||||
this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
|
||||
this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
|
||||
this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
|
||||
this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
|
||||
this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Starts the Gamepad event handling.
|
||||
* This MUST be called manually before Phaser will start polling the Gamepad API.
|
||||
*
|
||||
* @method Phaser.Gamepad#start
|
||||
*/
|
||||
start: function () {
|
||||
|
||||
if (this._active)
|
||||
{
|
||||
// Avoid setting multiple listeners
|
||||
return;
|
||||
}
|
||||
|
||||
this._active = true;
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._ongamepadconnected = function(event) {
|
||||
var newPad = event.gamepad;
|
||||
_this._rawPads.push(newPad);
|
||||
_this._gamepads[newPad.index].connect(newPad);
|
||||
};
|
||||
|
||||
window.addEventListener('gamepadconnected', this._ongamepadconnected, false);
|
||||
|
||||
this._ongamepaddisconnected = function(event) {
|
||||
|
||||
var removedPad = event.gamepad;
|
||||
|
||||
for (var i in _this._rawPads)
|
||||
{
|
||||
if (_this._rawPads[i].index === removedPad.index)
|
||||
{
|
||||
_this._rawPads.splice(i,1);
|
||||
}
|
||||
}
|
||||
_this._gamepads[removedPad.index].disconnect();
|
||||
};
|
||||
|
||||
window.addEventListener('gamepaddisconnected', this._ongamepaddisconnected, false);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Main gamepad update loop. Should not be called manually.
|
||||
* @method Phaser.Gamepad#update
|
||||
* @private
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
this._pollGamepads();
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
if (this._gamepads[i]._connected)
|
||||
{
|
||||
this._gamepads[i].pollStatus();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updating connected gamepads (for Google Chrome).
|
||||
* Should not be called manually.
|
||||
* @method Phaser.Gamepad#_pollGamepads
|
||||
* @private
|
||||
*/
|
||||
_pollGamepads: function () {
|
||||
|
||||
var rawGamepads = navigator.getGamepads || (navigator.webkitGetGamepads && navigator.webkitGetGamepads()) || navigator.webkitGamepads;
|
||||
|
||||
if (rawGamepads)
|
||||
{
|
||||
this._rawPads = [];
|
||||
|
||||
var gamepadsChanged = false;
|
||||
|
||||
for (var i = 0; i < rawGamepads.length; i++)
|
||||
{
|
||||
if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
|
||||
{
|
||||
gamepadsChanged = true;
|
||||
this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
|
||||
}
|
||||
|
||||
if (rawGamepads[i])
|
||||
{
|
||||
this._rawPads.push(rawGamepads[i]);
|
||||
}
|
||||
|
||||
// Support max 4 pads at the moment
|
||||
if (i === 3)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (gamepadsChanged)
|
||||
{
|
||||
var validConnections = { rawIndices: {}, padIndices: {} };
|
||||
var singlePad;
|
||||
|
||||
for (var j = 0; j < this._gamepads.length; j++)
|
||||
{
|
||||
singlePad = this._gamepads[j];
|
||||
|
||||
if (singlePad.connected)
|
||||
{
|
||||
for (var k = 0; k < this._rawPads.length; k++)
|
||||
{
|
||||
if (this._rawPads[k].index === singlePad.index)
|
||||
{
|
||||
validConnections.rawIndices[singlePad.index] = true;
|
||||
validConnections.padIndices[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var l = 0; l < this._gamepads.length; l++)
|
||||
{
|
||||
singlePad = this._gamepads[l];
|
||||
|
||||
if (validConnections.padIndices[l])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this._rawPads.length < 1)
|
||||
{
|
||||
singlePad.disconnect();
|
||||
}
|
||||
|
||||
for (var m = 0; m < this._rawPads.length; m++)
|
||||
{
|
||||
if (validConnections.padIndices[l])
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var rawPad = this._rawPads[m];
|
||||
|
||||
if (rawPad)
|
||||
{
|
||||
if (validConnections.rawIndices[rawPad.index])
|
||||
{
|
||||
singlePad.disconnect();
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
singlePad.connect(rawPad);
|
||||
validConnections.rawIndices[rawPad.index] = true;
|
||||
validConnections.padIndices[l] = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
singlePad.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets the deadZone variable for all four gamepads
|
||||
* @method Phaser.Gamepad#setDeadZones
|
||||
*/
|
||||
setDeadZones: function (value) {
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
this._gamepads[i].deadZone = value;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops the Gamepad event handling.
|
||||
*
|
||||
* @method Phaser.Gamepad#stop
|
||||
*/
|
||||
stop: function () {
|
||||
|
||||
this._active = false;
|
||||
|
||||
window.removeEventListener('gamepadconnected', this._ongamepadconnected);
|
||||
window.removeEventListener('gamepaddisconnected', this._ongamepaddisconnected);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset all buttons/axes of all gamepads
|
||||
* @method Phaser.Gamepad#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
this.update();
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
this._gamepads[i].reset();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
|
||||
* @method Phaser.Gamepad#justPressed
|
||||
* @param {number} buttonCode - The buttonCode of the button to check for.
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
|
||||
* @return {boolean} True if the button is just pressed otherwise false.
|
||||
*/
|
||||
justPressed: function (buttonCode, duration) {
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
if (this._gamepads[i].justPressed(buttonCode, duration) === true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms).
|
||||
* @method Phaser.Gamepad#justPressed
|
||||
* @param {number} buttonCode - The buttonCode of the button to check for.
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
|
||||
* @return {boolean} True if the button is just released otherwise false.
|
||||
*/
|
||||
justReleased: function (buttonCode, duration) {
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
if (this._gamepads[i].justReleased(buttonCode, duration) === true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the button is currently pressed down, on ANY gamepad.
|
||||
* @method Phaser.Gamepad#isDown
|
||||
* @param {number} buttonCode - The buttonCode of the button to check for.
|
||||
* @return {boolean} True if a button is currently down.
|
||||
*/
|
||||
isDown: function (buttonCode) {
|
||||
|
||||
for (var i = 0; i < this._gamepads.length; i++)
|
||||
{
|
||||
if (this._gamepads[i].isDown(buttonCode) === true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
|
||||
|
||||
/**
|
||||
* If the gamepad input is active or not - if not active it should not be updated from Input.js
|
||||
* @name Phaser.Gamepad#active
|
||||
* @property {boolean} active - If the gamepad input is active or not.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "active", {
|
||||
|
||||
get: function () {
|
||||
return this._active;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Whether or not gamepads are supported in current browser.
|
||||
* @name Phaser.Gamepad#supported
|
||||
* @property {boolean} supported - Whether or not gamepads are supported in current browser.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
|
||||
|
||||
get: function () {
|
||||
return this._gamepadSupportAvailable;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* How many live gamepads are currently connected.
|
||||
* @name Phaser.Gamepad#padsConnected
|
||||
* @property {boolean} padsConnected - How many live gamepads are currently connected.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
|
||||
|
||||
get: function () {
|
||||
return this._rawPads.length;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gamepad #1
|
||||
* @name Phaser.Gamepad#pad1
|
||||
* @property {boolean} pad1 - Gamepad #1;
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
|
||||
|
||||
get: function () {
|
||||
return this._gamepads[0];
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gamepad #2
|
||||
* @name Phaser.Gamepad#pad2
|
||||
* @property {boolean} pad2 - Gamepad #2
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
|
||||
|
||||
get: function () {
|
||||
return this._gamepads[1];
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gamepad #3
|
||||
* @name Phaser.Gamepad#pad3
|
||||
* @property {boolean} pad3 - Gamepad #3
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
|
||||
|
||||
get: function () {
|
||||
return this._gamepads[2];
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gamepad #4
|
||||
* @name Phaser.Gamepad#pad4
|
||||
* @property {boolean} pad4 - Gamepad #4
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
|
||||
|
||||
get: function () {
|
||||
return this._gamepads[3];
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Phaser.Gamepad.BUTTON_0 = 0;
|
||||
Phaser.Gamepad.BUTTON_1 = 1;
|
||||
Phaser.Gamepad.BUTTON_2 = 2;
|
||||
Phaser.Gamepad.BUTTON_3 = 3;
|
||||
Phaser.Gamepad.BUTTON_4 = 4;
|
||||
Phaser.Gamepad.BUTTON_5 = 5;
|
||||
Phaser.Gamepad.BUTTON_6 = 6;
|
||||
Phaser.Gamepad.BUTTON_7 = 7;
|
||||
Phaser.Gamepad.BUTTON_8 = 8;
|
||||
Phaser.Gamepad.BUTTON_9 = 9;
|
||||
Phaser.Gamepad.BUTTON_10 = 10;
|
||||
Phaser.Gamepad.BUTTON_11 = 11;
|
||||
Phaser.Gamepad.BUTTON_12 = 12;
|
||||
Phaser.Gamepad.BUTTON_13 = 13;
|
||||
Phaser.Gamepad.BUTTON_14 = 14;
|
||||
Phaser.Gamepad.BUTTON_15 = 15;
|
||||
|
||||
Phaser.Gamepad.AXIS_0 = 0;
|
||||
Phaser.Gamepad.AXIS_1 = 1;
|
||||
Phaser.Gamepad.AXIS_2 = 2;
|
||||
Phaser.Gamepad.AXIS_3 = 3;
|
||||
Phaser.Gamepad.AXIS_4 = 4;
|
||||
Phaser.Gamepad.AXIS_5 = 5;
|
||||
Phaser.Gamepad.AXIS_6 = 6;
|
||||
Phaser.Gamepad.AXIS_7 = 7;
|
||||
Phaser.Gamepad.AXIS_8 = 8;
|
||||
Phaser.Gamepad.AXIS_9 = 9;
|
||||
|
||||
// Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
|
||||
// - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
|
||||
// In other words - discrepancies when using gamepads.
|
||||
|
||||
Phaser.Gamepad.XBOX360_A = 0;
|
||||
Phaser.Gamepad.XBOX360_B = 1;
|
||||
Phaser.Gamepad.XBOX360_X = 2;
|
||||
Phaser.Gamepad.XBOX360_Y = 3;
|
||||
Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
|
||||
Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
|
||||
Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
|
||||
Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
|
||||
Phaser.Gamepad.XBOX360_BACK = 8;
|
||||
Phaser.Gamepad.XBOX360_START = 9;
|
||||
Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
|
||||
Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
|
||||
|
||||
Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
|
||||
Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
|
||||
Phaser.Gamepad.XBOX360_DPAD_UP = 12;
|
||||
Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
|
||||
|
||||
Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
|
||||
Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
|
||||
Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
|
||||
Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
|
||||
175
src/input/GamepadButton.js
Normal file
175
src/input/GamepadButton.js
Normal file
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* @author @karlmacklin <tacklemcclean@gmail.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.GamepadButton
|
||||
* @classdesc If you need more fine-grained control over the handling of specific buttons you can create and use Phaser.GamepadButton objects.
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {number} buttoncode - The button code this GamepadButton is responsible for.
|
||||
*/
|
||||
Phaser.GamepadButton = function (game, buttoncode) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} isDown - The "down" state of the button.
|
||||
* @default
|
||||
*/
|
||||
this.isDown = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isUp - The "up" state of the button.
|
||||
* @default
|
||||
*/
|
||||
this.isUp = true;
|
||||
|
||||
/**
|
||||
* @property {number} timeDown - The timestamp when the button was last pressed down.
|
||||
* @default
|
||||
*/
|
||||
this.timeDown = 0;
|
||||
|
||||
/**
|
||||
* If the button is down this value holds the duration of that button press and is constantly updated.
|
||||
* If the button is up it holds the duration of the previous down session.
|
||||
* @property {number} duration - The number of milliseconds this button has been held down for.
|
||||
* @default
|
||||
*/
|
||||
this.duration = 0;
|
||||
|
||||
/**
|
||||
* @property {number} timeUp - The timestamp when the button was last released.
|
||||
* @default
|
||||
*/
|
||||
this.timeUp = 0;
|
||||
|
||||
/**
|
||||
* @property {number} repeats - If a button is held down this holds down the number of times the button has 'repeated'.
|
||||
* @default
|
||||
*/
|
||||
this.repeats = 0;
|
||||
|
||||
/**
|
||||
* @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers)
|
||||
* @default
|
||||
*/
|
||||
this.value = 0;
|
||||
|
||||
/**
|
||||
* @property {number} buttonCode - The buttoncode of this button.
|
||||
*/
|
||||
this.buttonCode = buttoncode;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onDown - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
|
||||
*/
|
||||
this.onDown = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onUp - This Signal is dispatched every time this GamepadButton is pressed down. It is only dispatched once (until the button is released again).
|
||||
*/
|
||||
this.onUp = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onFloat - This Signal is dispatched every time this GamepadButton changes floating value (between (but not exactly) 0 and 1)
|
||||
*/
|
||||
this.onFloat = new Phaser.Signal();
|
||||
|
||||
};
|
||||
|
||||
Phaser.GamepadButton.prototype = {
|
||||
|
||||
/**
|
||||
* Called automatically by Phaser.SinglePad.
|
||||
* @method Phaser.GamepadButton#processButtonDown
|
||||
* @param {Object} value - Button value
|
||||
* @protected
|
||||
*/
|
||||
processButtonDown: function (value) {
|
||||
|
||||
if (this.isDown)
|
||||
{
|
||||
this.duration = this.game.time.now - this.timeDown;
|
||||
this.repeats++;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.isDown = true;
|
||||
this.isUp = false;
|
||||
this.timeDown = this.game.time.now;
|
||||
this.duration = 0;
|
||||
this.repeats = 0;
|
||||
this.value = value;
|
||||
|
||||
this.onDown.dispatch(this, value);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called automatically by Phaser.SinglePad.
|
||||
* @method Phaser.GamepadButton#processButtonUp
|
||||
* @param {Object} value - Button value
|
||||
* @protected
|
||||
*/
|
||||
processButtonUp: function (value) {
|
||||
|
||||
this.isDown = false;
|
||||
this.isUp = true;
|
||||
this.timeUp = this.game.time.now;
|
||||
this.value = value;
|
||||
|
||||
this.onUp.dispatch(this, value);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called automatically by Phaser.Gamepad.
|
||||
* @method Phaser.GamepadButton#processButtonFloat
|
||||
* @param {Object} value - Button value
|
||||
* @protected
|
||||
*/
|
||||
processButtonFloat: function (value) {
|
||||
|
||||
this.value = value;
|
||||
this.onFloat.dispatch(this, value);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just pressed" state of this button. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
|
||||
* @method Phaser.GamepadButton#justPressed
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
|
||||
* @return {boolean} True if the button is just pressed otherwise false.
|
||||
*/
|
||||
justPressed: function (duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 250; }
|
||||
|
||||
return (this.isDown && this.duration < duration);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just released" state of this button. Just released is considered as being true if the button was released within the duration given (default 250ms).
|
||||
* @method Phaser.GamepadButton#justPressed
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
|
||||
* @return {boolean} True if the button is just pressed otherwise false.
|
||||
*/
|
||||
justReleased: function (duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 250; }
|
||||
|
||||
return (this.isDown === false && (this.game.time.now - this.timeUp < duration));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.GamepadButton.prototype.constructor = Phaser.GamepadButton;
|
||||
1003
src/input/Input.js
Normal file
1003
src/input/Input.js
Normal file
File diff suppressed because it is too large
Load Diff
1410
src/input/InputHandler.js
Normal file
1410
src/input/InputHandler.js
Normal file
File diff suppressed because it is too large
Load Diff
248
src/input/Key.js
Normal file
248
src/input/Key.js
Normal file
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.Key
|
||||
* @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {number} keycode - The key code this Key is responsible for.
|
||||
*/
|
||||
Phaser.Key = function (game, keycode) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} enabled - An enabled key processes its update and dispatches events. You can toggle this at run-time to disable a key without deleting it.
|
||||
* @default
|
||||
*/
|
||||
this.enabled = true;
|
||||
|
||||
/**
|
||||
* @property {object} event - Stores the most recent DOM event.
|
||||
* @readonly
|
||||
*/
|
||||
this.event = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} isDown - The "down" state of the key.
|
||||
* @default
|
||||
*/
|
||||
this.isDown = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isUp - The "up" state of the key.
|
||||
* @default
|
||||
*/
|
||||
this.isUp = true;
|
||||
|
||||
/**
|
||||
* @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
|
||||
* @default
|
||||
*/
|
||||
this.altKey = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
|
||||
* @default
|
||||
*/
|
||||
this.ctrlKey = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
|
||||
* @default
|
||||
*/
|
||||
this.shiftKey = false;
|
||||
|
||||
/**
|
||||
* @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
|
||||
*/
|
||||
this.timeDown = 0;
|
||||
|
||||
/**
|
||||
* If the key is down this value holds the duration of that key press and is constantly updated.
|
||||
* If the key is up it holds the duration of the previous down session.
|
||||
* @property {number} duration - The number of milliseconds this key has been held down for.
|
||||
* @default
|
||||
*/
|
||||
this.duration = 0;
|
||||
|
||||
/**
|
||||
* @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
|
||||
* @default
|
||||
*/
|
||||
this.timeUp = -2500;
|
||||
|
||||
/**
|
||||
* @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
|
||||
* @default
|
||||
*/
|
||||
this.repeats = 0;
|
||||
|
||||
/**
|
||||
* @property {number} keyCode - The keycode of this key.
|
||||
*/
|
||||
this.keyCode = keycode;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
|
||||
*/
|
||||
this.onDown = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
|
||||
*/
|
||||
this.onHoldCallback = null;
|
||||
|
||||
/**
|
||||
* @property {object} onHoldContext - The context under which the onHoldCallback will be called.
|
||||
*/
|
||||
this.onHoldContext = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
|
||||
*/
|
||||
this.onUp = new Phaser.Signal();
|
||||
|
||||
};
|
||||
|
||||
Phaser.Key.prototype = {
|
||||
|
||||
update: function () {
|
||||
|
||||
if (!this.enabled) { return; }
|
||||
|
||||
if (this.isDown)
|
||||
{
|
||||
this.duration = this.game.time.now - this.timeDown;
|
||||
this.repeats++;
|
||||
|
||||
if (this.onHoldCallback)
|
||||
{
|
||||
this.onHoldCallback.call(this.onHoldContext, this);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called automatically by Phaser.Keyboard.
|
||||
* @method Phaser.Key#processKeyDown
|
||||
* @param {KeyboardEvent} event.
|
||||
* @protected
|
||||
*/
|
||||
processKeyDown: function (event) {
|
||||
|
||||
if (!this.enabled) { return; }
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.isDown)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.altKey = event.altKey;
|
||||
this.ctrlKey = event.ctrlKey;
|
||||
this.shiftKey = event.shiftKey;
|
||||
|
||||
this.isDown = true;
|
||||
this.isUp = false;
|
||||
this.timeDown = this.game.time.now;
|
||||
this.duration = 0;
|
||||
this.repeats = 0;
|
||||
|
||||
this.onDown.dispatch(this);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called automatically by Phaser.Keyboard.
|
||||
* @method Phaser.Key#processKeyUp
|
||||
* @param {KeyboardEvent} event.
|
||||
* @protected
|
||||
*/
|
||||
processKeyUp: function (event) {
|
||||
|
||||
if (!this.enabled) { return; }
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.isUp)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.isDown = false;
|
||||
this.isUp = true;
|
||||
this.timeUp = this.game.time.now;
|
||||
this.duration = this.game.time.now - this.timeDown;
|
||||
|
||||
this.onUp.dispatch(this);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the state of this Key. This sets isDown to false, isUp to true, resets the time to be the current time and clears any callbacks
|
||||
* associated with the onDown and onUp events and nulls the onHoldCallback if set.
|
||||
*
|
||||
* @method Phaser.Key#reset
|
||||
* @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to this Key. A hard reset will.
|
||||
*/
|
||||
reset: function (hard) {
|
||||
|
||||
if (typeof hard === 'undefined') { hard = true; }
|
||||
|
||||
this.isDown = false;
|
||||
this.isUp = true;
|
||||
this.timeUp = this.game.time.now;
|
||||
this.duration = this.game.time.now - this.timeDown;
|
||||
this.enabled = true;
|
||||
|
||||
if (hard)
|
||||
{
|
||||
this.onDown.removeAll();
|
||||
this.onUp.removeAll();
|
||||
this.onHoldCallback = null;
|
||||
this.onHoldContext = null;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
|
||||
* @method Phaser.Key#justPressed
|
||||
* @param {number} [duration=50] - The duration below which the key is considered as being just pressed.
|
||||
* @return {boolean} True if the key is just pressed otherwise false.
|
||||
*/
|
||||
justPressed: function (duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 50; }
|
||||
|
||||
return (this.isDown && this.duration < duration);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
|
||||
* @method Phaser.Key#justReleased
|
||||
* @param {number} [duration=50] - The duration below which the key is considered as being just released.
|
||||
* @return {boolean} True if the key is just released otherwise false.
|
||||
*/
|
||||
justReleased: function (duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 50; }
|
||||
|
||||
return (!this.isDown && ((this.game.time.now - this.timeUp) < duration));
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Key.prototype.constructor = Phaser.Key;
|
||||
549
src/input/Keyboard.js
Normal file
549
src/input/Keyboard.js
Normal file
@@ -0,0 +1,549 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Keyboard class handles looking after keyboard input for your game.
|
||||
* It will recognise and respond to key presses and dispatch the required events.
|
||||
* Please be aware that lots of keyboards are unable to process certain combinations of keys due to hardware
|
||||
* limitations known as ghosting. Full details here: http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/
|
||||
*
|
||||
* @class Phaser.Keyboard
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Keyboard = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored.
|
||||
* @property {boolean} disabled - The disabled state of the Keyboard.
|
||||
* @default
|
||||
*/
|
||||
this.disabled = false;
|
||||
|
||||
/**
|
||||
* @property {Object} event - The most recent DOM event. This is updated every time a new key is pressed or released.
|
||||
*/
|
||||
this.event = null;
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which the callbacks are run.
|
||||
*/
|
||||
this.callbackContext = this;
|
||||
|
||||
/**
|
||||
* @property {function} onDownCallback - This callback is invoked every time a key is pressed down.
|
||||
*/
|
||||
this.onDownCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onUpCallback - This callback is invoked every time a key is released.
|
||||
*/
|
||||
this.onUpCallback = null;
|
||||
|
||||
/**
|
||||
* @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
|
||||
* @private
|
||||
*/
|
||||
this._keys = [];
|
||||
|
||||
/**
|
||||
* @property {array} _capture - The array the key capture values are stored in.
|
||||
* @private
|
||||
*/
|
||||
this._capture = [];
|
||||
|
||||
/**
|
||||
* @property {function} _onKeyDown
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onKeyDown = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onKeyUp
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._onKeyUp = null;
|
||||
|
||||
/**
|
||||
* @property {number} _i - Internal cache var
|
||||
* @private
|
||||
*/
|
||||
this._i = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Keyboard.prototype = {
|
||||
|
||||
/**
|
||||
* Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
|
||||
*
|
||||
* @method Phaser.Keyboard#addCallbacks
|
||||
* @param {Object} context - The context under which the callbacks are run.
|
||||
* @param {function} onDown - This callback is invoked every time a key is pressed down.
|
||||
* @param {function} [onUp=null] - This callback is invoked every time a key is released.
|
||||
*/
|
||||
addCallbacks: function (context, onDown, onUp) {
|
||||
|
||||
this.callbackContext = context;
|
||||
this.onDownCallback = onDown;
|
||||
|
||||
if (typeof onUp !== 'undefined')
|
||||
{
|
||||
this.onUpCallback = onUp;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
|
||||
* The Key object can then be polled, have events attached to it, etc.
|
||||
*
|
||||
* @method Phaser.Keyboard#addKey
|
||||
* @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
|
||||
* @return {Phaser.Key} The Key object which you can store locally and reference directly.
|
||||
*/
|
||||
addKey: function (keycode) {
|
||||
|
||||
if (!this._keys[keycode])
|
||||
{
|
||||
this._keys[keycode] = new Phaser.Key(this.game, keycode);
|
||||
|
||||
this.addKeyCapture(keycode);
|
||||
}
|
||||
|
||||
return this._keys[keycode];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes a Key object from the Keyboard manager.
|
||||
*
|
||||
* @method Phaser.Keyboard#removeKey
|
||||
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
|
||||
*/
|
||||
removeKey: function (keycode) {
|
||||
|
||||
if (this._keys[keycode])
|
||||
{
|
||||
this._keys[keycode] = null;
|
||||
|
||||
this.removeKeyCapture(keycode);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
|
||||
*
|
||||
* @method Phaser.Keyboard#createCursorKeys
|
||||
* @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object.
|
||||
*/
|
||||
createCursorKeys: function () {
|
||||
|
||||
return {
|
||||
up: this.addKey(Phaser.Keyboard.UP),
|
||||
down: this.addKey(Phaser.Keyboard.DOWN),
|
||||
left: this.addKey(Phaser.Keyboard.LEFT),
|
||||
right: this.addKey(Phaser.Keyboard.RIGHT)
|
||||
};
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
|
||||
* This is called automatically by Phaser.Input and should not normally be invoked directly.
|
||||
*
|
||||
* @method Phaser.Keyboard#start
|
||||
*/
|
||||
start: function () {
|
||||
|
||||
if (this._onKeyDown !== null)
|
||||
{
|
||||
// Avoid setting multiple listeners
|
||||
return;
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._onKeyDown = function (event) {
|
||||
return _this.processKeyDown(event);
|
||||
};
|
||||
|
||||
this._onKeyUp = function (event) {
|
||||
return _this.processKeyUp(event);
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', this._onKeyDown, false);
|
||||
window.addEventListener('keyup', this._onKeyUp, false);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
|
||||
*
|
||||
* @method Phaser.Keyboard#stop
|
||||
*/
|
||||
stop: function () {
|
||||
|
||||
window.removeEventListener('keydown', this._onKeyDown);
|
||||
window.removeEventListener('keyup', this._onKeyUp);
|
||||
|
||||
this._onKeyDown = null;
|
||||
this._onKeyUp = null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
|
||||
* Also clears all key captures and currently created Key objects.
|
||||
*
|
||||
* @method Phaser.Keyboard#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.stop();
|
||||
|
||||
this.clearCaptures();
|
||||
|
||||
this._keys.length = 0;
|
||||
this._i = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
|
||||
* There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
|
||||
* You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser.
|
||||
* Pass in either a single keycode or an array/hash of keycodes.
|
||||
*
|
||||
* @method Phaser.Keyboard#addKeyCapture
|
||||
* @param {Any} keycode - Either a single numeric keycode or an array/hash of keycodes: [65, 67, 68].
|
||||
*/
|
||||
addKeyCapture: function (keycode) {
|
||||
|
||||
if (typeof keycode === 'object')
|
||||
{
|
||||
for (var key in keycode)
|
||||
{
|
||||
this._capture[keycode[key]] = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this._capture[keycode] = true;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes an existing key capture.
|
||||
*
|
||||
* @method Phaser.Keyboard#removeKeyCapture
|
||||
* @param {number} keycode
|
||||
*/
|
||||
removeKeyCapture: function (keycode) {
|
||||
|
||||
delete this._capture[keycode];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear all set key captures.
|
||||
*
|
||||
* @method Phaser.Keyboard#clearCaptures
|
||||
*/
|
||||
clearCaptures: function () {
|
||||
|
||||
this._capture = {};
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates all currently defined keys.
|
||||
*
|
||||
* @method Phaser.Keyboard#update
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
this._i = this._keys.length;
|
||||
|
||||
while (this._i--)
|
||||
{
|
||||
if (this._keys[this._i])
|
||||
{
|
||||
this._keys[this._i].update();
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Process the keydown event.
|
||||
*
|
||||
* @method Phaser.Keyboard#processKeyDown
|
||||
* @param {KeyboardEvent} event
|
||||
* @protected
|
||||
*/
|
||||
processKeyDown: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The event is being captured but another hotkey may need it
|
||||
if (this._capture[event.keyCode])
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (this.onDownCallback)
|
||||
{
|
||||
this.onDownCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (!this._keys[event.keyCode])
|
||||
{
|
||||
this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
|
||||
}
|
||||
|
||||
this._keys[event.keyCode].processKeyDown(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Process the keyup event.
|
||||
*
|
||||
* @method Phaser.Keyboard#processKeyUp
|
||||
* @param {KeyboardEvent} event
|
||||
* @protected
|
||||
*/
|
||||
processKeyUp: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._capture[event.keyCode])
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (this.onUpCallback)
|
||||
{
|
||||
this.onUpCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (!this._keys[event.keyCode])
|
||||
{
|
||||
this._keys[event.keyCode] = new Phaser.Key(this.game, event.keyCode);
|
||||
}
|
||||
|
||||
this._keys[event.keyCode].processKeyUp(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets all Keys.
|
||||
*
|
||||
* @method Phaser.Keyboard#reset
|
||||
* @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
|
||||
*/
|
||||
reset: function (hard) {
|
||||
|
||||
if (typeof hard === 'undefined') { hard = true; }
|
||||
|
||||
this.event = null;
|
||||
|
||||
var i = this._keys.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
if (this._keys[i])
|
||||
{
|
||||
this._keys[i].reset(hard);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just pressed" state of the key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms)
|
||||
*
|
||||
* @method Phaser.Keyboard#justPressed
|
||||
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
|
||||
* @param {number} [duration=50] - The duration below which the key is considered as being just pressed.
|
||||
* @return {boolean} True if the key is just pressed otherwise false.
|
||||
*/
|
||||
justPressed: function (keycode, duration) {
|
||||
|
||||
if (typeof duration === 'undefined') { duration = 50; }
|
||||
|
||||
if (this._keys[keycode])
|
||||
{
|
||||
return this._keys[keycode].justPressed(duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms)
|
||||
*
|
||||
* @method Phaser.Keyboard#justReleased
|
||||
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
|
||||
* @param {number} [duration=50] - The duration below which the key is considered as being just released.
|
||||
* @return {boolean} True if the key is just released otherwise false.
|
||||
*/
|
||||
justReleased: function (keycode, duration) {
|
||||
|
||||
if (typeof duration === 'undefined') { duration = 50; }
|
||||
|
||||
if (this._keys[keycode])
|
||||
{
|
||||
return this._keys[keycode].justReleased(duration);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
|
||||
*
|
||||
* @method Phaser.Keyboard#isDown
|
||||
* @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACEBAR
|
||||
* @return {boolean} True if the key is currently down.
|
||||
*/
|
||||
isDown: function (keycode) {
|
||||
|
||||
if (this._keys[keycode])
|
||||
{
|
||||
return this._keys[keycode].isDown;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
|
||||
|
||||
Phaser.Keyboard.A = "A".charCodeAt(0);
|
||||
Phaser.Keyboard.B = "B".charCodeAt(0);
|
||||
Phaser.Keyboard.C = "C".charCodeAt(0);
|
||||
Phaser.Keyboard.D = "D".charCodeAt(0);
|
||||
Phaser.Keyboard.E = "E".charCodeAt(0);
|
||||
Phaser.Keyboard.F = "F".charCodeAt(0);
|
||||
Phaser.Keyboard.G = "G".charCodeAt(0);
|
||||
Phaser.Keyboard.H = "H".charCodeAt(0);
|
||||
Phaser.Keyboard.I = "I".charCodeAt(0);
|
||||
Phaser.Keyboard.J = "J".charCodeAt(0);
|
||||
Phaser.Keyboard.K = "K".charCodeAt(0);
|
||||
Phaser.Keyboard.L = "L".charCodeAt(0);
|
||||
Phaser.Keyboard.M = "M".charCodeAt(0);
|
||||
Phaser.Keyboard.N = "N".charCodeAt(0);
|
||||
Phaser.Keyboard.O = "O".charCodeAt(0);
|
||||
Phaser.Keyboard.P = "P".charCodeAt(0);
|
||||
Phaser.Keyboard.Q = "Q".charCodeAt(0);
|
||||
Phaser.Keyboard.R = "R".charCodeAt(0);
|
||||
Phaser.Keyboard.S = "S".charCodeAt(0);
|
||||
Phaser.Keyboard.T = "T".charCodeAt(0);
|
||||
Phaser.Keyboard.U = "U".charCodeAt(0);
|
||||
Phaser.Keyboard.V = "V".charCodeAt(0);
|
||||
Phaser.Keyboard.W = "W".charCodeAt(0);
|
||||
Phaser.Keyboard.X = "X".charCodeAt(0);
|
||||
Phaser.Keyboard.Y = "Y".charCodeAt(0);
|
||||
Phaser.Keyboard.Z = "Z".charCodeAt(0);
|
||||
Phaser.Keyboard.ZERO = "0".charCodeAt(0);
|
||||
Phaser.Keyboard.ONE = "1".charCodeAt(0);
|
||||
Phaser.Keyboard.TWO = "2".charCodeAt(0);
|
||||
Phaser.Keyboard.THREE = "3".charCodeAt(0);
|
||||
Phaser.Keyboard.FOUR = "4".charCodeAt(0);
|
||||
Phaser.Keyboard.FIVE = "5".charCodeAt(0);
|
||||
Phaser.Keyboard.SIX = "6".charCodeAt(0);
|
||||
Phaser.Keyboard.SEVEN = "7".charCodeAt(0);
|
||||
Phaser.Keyboard.EIGHT = "8".charCodeAt(0);
|
||||
Phaser.Keyboard.NINE = "9".charCodeAt(0);
|
||||
Phaser.Keyboard.NUMPAD_0 = 96;
|
||||
Phaser.Keyboard.NUMPAD_1 = 97;
|
||||
Phaser.Keyboard.NUMPAD_2 = 98;
|
||||
Phaser.Keyboard.NUMPAD_3 = 99;
|
||||
Phaser.Keyboard.NUMPAD_4 = 100;
|
||||
Phaser.Keyboard.NUMPAD_5 = 101;
|
||||
Phaser.Keyboard.NUMPAD_6 = 102;
|
||||
Phaser.Keyboard.NUMPAD_7 = 103;
|
||||
Phaser.Keyboard.NUMPAD_8 = 104;
|
||||
Phaser.Keyboard.NUMPAD_9 = 105;
|
||||
Phaser.Keyboard.NUMPAD_MULTIPLY = 106;
|
||||
Phaser.Keyboard.NUMPAD_ADD = 107;
|
||||
Phaser.Keyboard.NUMPAD_ENTER = 108;
|
||||
Phaser.Keyboard.NUMPAD_SUBTRACT = 109;
|
||||
Phaser.Keyboard.NUMPAD_DECIMAL = 110;
|
||||
Phaser.Keyboard.NUMPAD_DIVIDE = 111;
|
||||
Phaser.Keyboard.F1 = 112;
|
||||
Phaser.Keyboard.F2 = 113;
|
||||
Phaser.Keyboard.F3 = 114;
|
||||
Phaser.Keyboard.F4 = 115;
|
||||
Phaser.Keyboard.F5 = 116;
|
||||
Phaser.Keyboard.F6 = 117;
|
||||
Phaser.Keyboard.F7 = 118;
|
||||
Phaser.Keyboard.F8 = 119;
|
||||
Phaser.Keyboard.F9 = 120;
|
||||
Phaser.Keyboard.F10 = 121;
|
||||
Phaser.Keyboard.F11 = 122;
|
||||
Phaser.Keyboard.F12 = 123;
|
||||
Phaser.Keyboard.F13 = 124;
|
||||
Phaser.Keyboard.F14 = 125;
|
||||
Phaser.Keyboard.F15 = 126;
|
||||
Phaser.Keyboard.COLON = 186;
|
||||
Phaser.Keyboard.EQUALS = 187;
|
||||
Phaser.Keyboard.UNDERSCORE = 189;
|
||||
Phaser.Keyboard.QUESTION_MARK = 191;
|
||||
Phaser.Keyboard.TILDE = 192;
|
||||
Phaser.Keyboard.OPEN_BRACKET = 219;
|
||||
Phaser.Keyboard.BACKWARD_SLASH = 220;
|
||||
Phaser.Keyboard.CLOSED_BRACKET = 221;
|
||||
Phaser.Keyboard.QUOTES = 222;
|
||||
Phaser.Keyboard.BACKSPACE = 8;
|
||||
Phaser.Keyboard.TAB = 9;
|
||||
Phaser.Keyboard.CLEAR = 12;
|
||||
Phaser.Keyboard.ENTER = 13;
|
||||
Phaser.Keyboard.SHIFT = 16;
|
||||
Phaser.Keyboard.CONTROL = 17;
|
||||
Phaser.Keyboard.ALT = 18;
|
||||
Phaser.Keyboard.CAPS_LOCK = 20;
|
||||
Phaser.Keyboard.ESC = 27;
|
||||
Phaser.Keyboard.SPACEBAR = 32;
|
||||
Phaser.Keyboard.PAGE_UP = 33;
|
||||
Phaser.Keyboard.PAGE_DOWN = 34;
|
||||
Phaser.Keyboard.END = 35;
|
||||
Phaser.Keyboard.HOME = 36;
|
||||
Phaser.Keyboard.LEFT = 37;
|
||||
Phaser.Keyboard.UP = 38;
|
||||
Phaser.Keyboard.RIGHT = 39;
|
||||
Phaser.Keyboard.DOWN = 40;
|
||||
Phaser.Keyboard.INSERT = 45;
|
||||
Phaser.Keyboard.DELETE = 46;
|
||||
Phaser.Keyboard.HELP = 47;
|
||||
Phaser.Keyboard.NUM_LOCK = 144;
|
||||
176
src/input/MSPointer.js
Normal file
176
src/input/MSPointer.js
Normal file
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser - MSPointer constructor.
|
||||
*
|
||||
* @class Phaser.MSPointer
|
||||
* @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects.
|
||||
* It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript.
|
||||
* http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.MSPointer = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which callbacks are called (defaults to game).
|
||||
*/
|
||||
this.callbackContext = this.game;
|
||||
|
||||
/**
|
||||
* You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
|
||||
* @property {boolean} disabled
|
||||
*/
|
||||
this.disabled = false;
|
||||
|
||||
/**
|
||||
* @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
|
||||
* @private
|
||||
*/
|
||||
this._onMSPointerDown = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
|
||||
* @private
|
||||
*/
|
||||
this._onMSPointerMove = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
|
||||
* @private
|
||||
*/
|
||||
this._onMSPointerUp = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.MSPointer.prototype = {
|
||||
|
||||
/**
|
||||
* Starts the event listeners running.
|
||||
* @method Phaser.MSPointer#start
|
||||
*/
|
||||
start: function () {
|
||||
|
||||
if (this._onMSPointerDown !== null)
|
||||
{
|
||||
// Avoid setting multiple listeners
|
||||
return;
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
if (this.game.device.mspointer === true)
|
||||
{
|
||||
this._onMSPointerDown = function (event) {
|
||||
return _this.onPointerDown(event);
|
||||
};
|
||||
|
||||
this._onMSPointerMove = function (event) {
|
||||
return _this.onPointerMove(event);
|
||||
};
|
||||
|
||||
this._onMSPointerUp = function (event) {
|
||||
return _this.onPointerUp(event);
|
||||
};
|
||||
|
||||
this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false);
|
||||
this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false);
|
||||
this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false);
|
||||
|
||||
// IE11+ uses non-prefix events
|
||||
this.game.renderer.view.addEventListener('pointerDown', this._onMSPointerDown, false);
|
||||
this.game.renderer.view.addEventListener('pointerMove', this._onMSPointerMove, false);
|
||||
this.game.renderer.view.addEventListener('pointerUp', this._onMSPointerUp, false);
|
||||
|
||||
this.game.renderer.view.style['-ms-content-zooming'] = 'none';
|
||||
this.game.renderer.view.style['-ms-touch-action'] = 'none';
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The function that handles the PointerDown event.
|
||||
* @method Phaser.MSPointer#onPointerDown
|
||||
* @param {PointerEvent} event
|
||||
*/
|
||||
onPointerDown: function (event) {
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.identifier = event.pointerId;
|
||||
|
||||
this.game.input.startPointer(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The function that handles the PointerMove event.
|
||||
* @method Phaser.MSPointer#onPointerMove
|
||||
* @param {PointerEvent } event
|
||||
*/
|
||||
onPointerMove: function (event) {
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.identifier = event.pointerId;
|
||||
|
||||
this.game.input.updatePointer(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The function that handles the PointerUp event.
|
||||
* @method Phaser.MSPointer#onPointerUp
|
||||
* @param {PointerEvent} event
|
||||
*/
|
||||
onPointerUp: function (event) {
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
event.identifier = event.pointerId;
|
||||
|
||||
this.game.input.stopPointer(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop the event listeners.
|
||||
* @method Phaser.MSPointer#stop
|
||||
*/
|
||||
stop: function () {
|
||||
|
||||
this.game.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown);
|
||||
this.game.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove);
|
||||
this.game.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp);
|
||||
|
||||
this.game.canvas.removeEventListener('pointerDown', this._onMSPointerDown);
|
||||
this.game.canvas.removeEventListener('pointerMove', this._onMSPointerMove);
|
||||
this.game.canvas.removeEventListener('pointerUp', this._onMSPointerUp);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
|
||||
442
src/input/Mouse.js
Normal file
442
src/input/Mouse.js
Normal file
@@ -0,0 +1,442 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.Mouse is responsible for handling all aspects of mouse interaction with the browser. It captures and processes mouse events.
|
||||
*
|
||||
* @class Phaser.Mouse
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Mouse = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which callbacks are called.
|
||||
*/
|
||||
this.callbackContext = this.game;
|
||||
|
||||
/**
|
||||
* @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
|
||||
*/
|
||||
this.mouseDownCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} mouseMoveCallback - A callback that can be fired when the mouse is moved while pressed down.
|
||||
*/
|
||||
this.mouseMoveCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
|
||||
*/
|
||||
this.mouseUpCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas.
|
||||
*/
|
||||
this.mouseOutCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout).
|
||||
*/
|
||||
this.mouseOverCallback = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propogate fully.
|
||||
*/
|
||||
this.capture = false;
|
||||
|
||||
/**
|
||||
* @property {number} button- The type of click, either: Phaser.Mouse.NO_BUTTON, Phaser.Mouse.LEFT_BUTTON, Phaser.Mouse.MIDDLE_BUTTON or Phaser.Mouse.RIGHT_BUTTON.
|
||||
* @default
|
||||
*/
|
||||
this.button = -1;
|
||||
|
||||
/**
|
||||
* @property {boolean} disabled - You can disable all Input by setting disabled = true. While set all new input related events will be ignored.
|
||||
* @default
|
||||
*/
|
||||
this.disabled = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
|
||||
* @default
|
||||
*/
|
||||
this.locked = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas.
|
||||
* @default
|
||||
*/
|
||||
this.stopOnGameOut = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
|
||||
* @default
|
||||
*/
|
||||
this.pointerLock = new Phaser.Signal();
|
||||
|
||||
/**
|
||||
* @property {MouseEvent} event - The browser mouse DOM event. Will be set to null if no mouse event has ever been received.
|
||||
* @default
|
||||
*/
|
||||
this.event = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMouseDown - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onMouseDown = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMouseMove - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onMouseMove = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMouseUp - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onMouseUp = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMouseOut - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onMouseOut = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onMouseOver - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onMouseOver = null;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Mouse.NO_BUTTON = -1;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Mouse.LEFT_BUTTON = 0;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Mouse.MIDDLE_BUTTON = 1;
|
||||
|
||||
/**
|
||||
* @constant
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Mouse.RIGHT_BUTTON = 2;
|
||||
|
||||
Phaser.Mouse.prototype = {
|
||||
|
||||
/**
|
||||
* Starts the event listeners running.
|
||||
* @method Phaser.Mouse#start
|
||||
*/
|
||||
start: function () {
|
||||
|
||||
if (this.game.device.android && this.game.device.chrome === false)
|
||||
{
|
||||
// Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._onMouseDown !== null)
|
||||
{
|
||||
// Avoid setting multiple listeners
|
||||
return;
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._onMouseDown = function (event) {
|
||||
return _this.onMouseDown(event);
|
||||
};
|
||||
|
||||
this._onMouseMove = function (event) {
|
||||
return _this.onMouseMove(event);
|
||||
};
|
||||
|
||||
this._onMouseUp = function (event) {
|
||||
return _this.onMouseUp(event);
|
||||
};
|
||||
|
||||
this._onMouseOut = function (event) {
|
||||
return _this.onMouseOut(event);
|
||||
};
|
||||
|
||||
this._onMouseOver = function (event) {
|
||||
return _this.onMouseOver(event);
|
||||
};
|
||||
|
||||
this.game.canvas.addEventListener('mousedown', this._onMouseDown, true);
|
||||
this.game.canvas.addEventListener('mousemove', this._onMouseMove, true);
|
||||
this.game.canvas.addEventListener('mouseup', this._onMouseUp, true);
|
||||
this.game.canvas.addEventListener('mouseover', this._onMouseOver, true);
|
||||
this.game.canvas.addEventListener('mouseout', this._onMouseOut, true);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the mouse down event from the browser.
|
||||
* @method Phaser.Mouse#onMouseDown
|
||||
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
onMouseDown: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.capture)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
this.button = event.button;
|
||||
|
||||
if (this.mouseDownCallback)
|
||||
{
|
||||
this.mouseDownCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event['identifier'] = 0;
|
||||
|
||||
this.game.input.mousePointer.start(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the mouse move event from the browser.
|
||||
* @method Phaser.Mouse#onMouseMove
|
||||
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
onMouseMove: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.capture)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (this.mouseMoveCallback)
|
||||
{
|
||||
this.mouseMoveCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event['identifier'] = 0;
|
||||
|
||||
this.game.input.mousePointer.move(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the mouse up event from the browser.
|
||||
* @method Phaser.Mouse#onMouseUp
|
||||
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
onMouseUp: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.capture)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
this.button = Phaser.Mouse.NO_BUTTON;
|
||||
|
||||
if (this.mouseUpCallback)
|
||||
{
|
||||
this.mouseUpCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
event['identifier'] = 0;
|
||||
|
||||
this.game.input.mousePointer.stop(event);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the mouse out event from the browser.
|
||||
*
|
||||
* @method Phaser.Mouse#onMouseOut
|
||||
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
onMouseOut: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.capture)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (this.mouseOutCallback)
|
||||
{
|
||||
this.mouseOutCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.game.input.mousePointer.withinGame = false;
|
||||
|
||||
if (this.stopOnGameOut)
|
||||
{
|
||||
event['identifier'] = 0;
|
||||
|
||||
this.game.input.mousePointer.stop(event);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the mouse over event from the browser.
|
||||
*
|
||||
* @method Phaser.Mouse#onMouseOver
|
||||
* @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
onMouseOver: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.capture)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
if (this.mouseOverCallback)
|
||||
{
|
||||
this.mouseOverCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.game.input.mousePointer.withinGame = true;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If the browser supports it you can request that the pointer be locked to the browser window.
|
||||
* This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
|
||||
* If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
|
||||
* @method Phaser.Mouse#requestPointerLock
|
||||
*/
|
||||
requestPointerLock: function () {
|
||||
|
||||
if (this.game.device.pointerLock)
|
||||
{
|
||||
var element = this.game.canvas;
|
||||
|
||||
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
|
||||
|
||||
element.requestPointerLock();
|
||||
|
||||
var _this = this;
|
||||
|
||||
this._pointerLockChange = function (event) {
|
||||
return _this.pointerLockChange(event);
|
||||
};
|
||||
|
||||
document.addEventListener('pointerlockchange', this._pointerLockChange, true);
|
||||
document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
|
||||
document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal pointerLockChange handler.
|
||||
* @method Phaser.Mouse#pointerLockChange
|
||||
* @param {pointerlockchange} event - The native event from the browser. This gets stored in Mouse.event.
|
||||
*/
|
||||
pointerLockChange: function (event) {
|
||||
|
||||
var element = this.game.canvas;
|
||||
|
||||
if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
|
||||
{
|
||||
// Pointer was successfully locked
|
||||
this.locked = true;
|
||||
this.pointerLock.dispatch(true, event);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Pointer was unlocked
|
||||
this.locked = false;
|
||||
this.pointerLock.dispatch(false, event);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal release pointer lock handler.
|
||||
* @method Phaser.Mouse#releasePointerLock
|
||||
*/
|
||||
releasePointerLock: function () {
|
||||
|
||||
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
|
||||
|
||||
document.exitPointerLock();
|
||||
|
||||
document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
|
||||
document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
|
||||
document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop the event listeners.
|
||||
* @method Phaser.Mouse#stop
|
||||
*/
|
||||
stop: function () {
|
||||
|
||||
this.game.canvas.removeEventListener('mousedown', this._onMouseDown, true);
|
||||
this.game.canvas.removeEventListener('mousemove', this._onMouseMove, true);
|
||||
this.game.canvas.removeEventListener('mouseup', this._onMouseUp, true);
|
||||
this.game.canvas.removeEventListener('mouseover', this._onMouseOver, true);
|
||||
this.game.canvas.removeEventListener('mouseout', this._onMouseOut, true);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Mouse.prototype.constructor = Phaser.Mouse;
|
||||
720
src/input/Pointer.js
Normal file
720
src/input/Pointer.js
Normal file
@@ -0,0 +1,720 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser - Pointer constructor.
|
||||
*
|
||||
* @class Phaser.Pointer
|
||||
* @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
|
||||
*/
|
||||
Phaser.Pointer = function (game, id) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
|
||||
*/
|
||||
this.id = id;
|
||||
|
||||
/**
|
||||
* @property {number} type - The const type of this object.
|
||||
* @readonly
|
||||
*/
|
||||
this.type = Phaser.POINTER;
|
||||
|
||||
/**
|
||||
* @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps.
|
||||
* @default
|
||||
*/
|
||||
this.exists = true;
|
||||
|
||||
/**
|
||||
* @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started.
|
||||
* @default
|
||||
*/
|
||||
this.identifier = 0;
|
||||
|
||||
/**
|
||||
* @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value.
|
||||
* @default
|
||||
*/
|
||||
this.pointerId = null;
|
||||
|
||||
/**
|
||||
* @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started.
|
||||
* @default
|
||||
*/
|
||||
this.target = null;
|
||||
|
||||
/**
|
||||
* @property {any} button - The button property of the Pointer as set by the DOM event when this Pointer is started.
|
||||
* @default
|
||||
*/
|
||||
this.button = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
|
||||
* @private
|
||||
* @default
|
||||
*/
|
||||
this._holdSent = false;
|
||||
|
||||
/**
|
||||
* @property {array} _history - Local private variable storing the short-term history of pointer movements.
|
||||
* @private
|
||||
*/
|
||||
this._history = [];
|
||||
|
||||
/**
|
||||
* @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur.
|
||||
* @private
|
||||
*/
|
||||
this._nextDrop = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} _stateReset - Monitor events outside of a state reset loop.
|
||||
* @private
|
||||
*/
|
||||
this._stateReset = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false.
|
||||
*/
|
||||
this.withinGame = false;
|
||||
|
||||
/**
|
||||
* @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
|
||||
*/
|
||||
this.clientX = -1;
|
||||
|
||||
/**
|
||||
* @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
|
||||
*/
|
||||
this.clientY = -1;
|
||||
|
||||
/**
|
||||
* @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document.
|
||||
*/
|
||||
this.pageX = -1;
|
||||
|
||||
/**
|
||||
* @property {number} pageY - The vertical coordinate of the Pointer relative to whole document.
|
||||
*/
|
||||
this.pageY = -1;
|
||||
|
||||
/**
|
||||
* @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen.
|
||||
*/
|
||||
this.screenX = -1;
|
||||
|
||||
/**
|
||||
* @property {number} screenY - The vertical coordinate of the Pointer relative to the screen.
|
||||
*/
|
||||
this.screenY = -1;
|
||||
|
||||
/**
|
||||
* @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event.
|
||||
* @default
|
||||
*/
|
||||
this.rawMovementX = 0;
|
||||
|
||||
/**
|
||||
* @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event.
|
||||
* @default
|
||||
*/
|
||||
this.rawMovementY = 0;
|
||||
|
||||
/**
|
||||
* @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event.
|
||||
* @default
|
||||
*/
|
||||
this.movementX = 0;
|
||||
|
||||
/**
|
||||
* @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event.
|
||||
* @default
|
||||
*/
|
||||
this.movementY = 0;
|
||||
|
||||
/**
|
||||
* @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale.
|
||||
* @default
|
||||
*/
|
||||
this.x = -1;
|
||||
|
||||
/**
|
||||
* @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale.
|
||||
* @default
|
||||
*/
|
||||
this.y = -1;
|
||||
|
||||
/**
|
||||
* @property {boolean} isMouse - If the Pointer is a mouse this is true, otherwise false.
|
||||
* @default
|
||||
*/
|
||||
this.isMouse = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isDown - If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true.
|
||||
* @default
|
||||
*/
|
||||
this.isDown = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} isUp - If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true.
|
||||
* @default
|
||||
*/
|
||||
this.isUp = true;
|
||||
|
||||
/**
|
||||
* @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
|
||||
* @default
|
||||
*/
|
||||
this.timeDown = 0;
|
||||
|
||||
/**
|
||||
* @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
|
||||
* @default
|
||||
*/
|
||||
this.timeUp = 0;
|
||||
|
||||
/**
|
||||
* @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
|
||||
* @default
|
||||
*/
|
||||
this.previousTapTime = 0;
|
||||
|
||||
/**
|
||||
* @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
|
||||
* @default
|
||||
*/
|
||||
this.totalTouches = 0;
|
||||
|
||||
/**
|
||||
* @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event.
|
||||
* @default
|
||||
*/
|
||||
this.msSinceLastClick = Number.MAX_VALUE;
|
||||
|
||||
/**
|
||||
* @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
|
||||
* @default
|
||||
*/
|
||||
this.targetObject = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
|
||||
* @default
|
||||
*/
|
||||
this.active = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
|
||||
*/
|
||||
this.position = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display.
|
||||
*/
|
||||
this.positionDown = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
|
||||
*/
|
||||
this.positionUp = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
|
||||
* The Circle size is 44px (Apples recommended "finger tip" size).
|
||||
* @property {Phaser.Circle} circle
|
||||
*/
|
||||
this.circle = new Phaser.Circle(0, 0, 44);
|
||||
|
||||
if (id === 0)
|
||||
{
|
||||
this.isMouse = true;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Pointer.prototype = {
|
||||
|
||||
/**
|
||||
* Called when the Pointer is pressed onto the touchscreen.
|
||||
* @method Phaser.Pointer#start
|
||||
* @param {any} event - The DOM event from the browser.
|
||||
*/
|
||||
start: function (event) {
|
||||
|
||||
if (event['pointerId'])
|
||||
{
|
||||
this.pointerId = event.pointerId;
|
||||
}
|
||||
|
||||
this.identifier = event.identifier;
|
||||
this.target = event.target;
|
||||
|
||||
if (typeof event.button !== 'undefined')
|
||||
{
|
||||
this.button = event.button;
|
||||
}
|
||||
|
||||
this._history = [];
|
||||
this.active = true;
|
||||
this.withinGame = true;
|
||||
this.isDown = true;
|
||||
this.isUp = false;
|
||||
|
||||
// Work out how long it has been since the last click
|
||||
this.msSinceLastClick = this.game.time.now - this.timeDown;
|
||||
this.timeDown = this.game.time.now;
|
||||
this._holdSent = false;
|
||||
|
||||
// This sets the x/y and other local values
|
||||
this.move(event, true);
|
||||
|
||||
// x and y are the old values here?
|
||||
this.positionDown.setTo(this.x, this.y);
|
||||
|
||||
if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
|
||||
{
|
||||
this.game.input.x = this.x;
|
||||
this.game.input.y = this.y;
|
||||
this.game.input.position.setTo(this.x, this.y);
|
||||
this.game.input.onDown.dispatch(this, event);
|
||||
this.game.input.resetSpeed(this.x, this.y);
|
||||
}
|
||||
|
||||
this._stateReset = false;
|
||||
this.totalTouches++;
|
||||
|
||||
if (!this.isMouse)
|
||||
{
|
||||
this.game.input.currentPointers++;
|
||||
}
|
||||
|
||||
if (this.targetObject !== null)
|
||||
{
|
||||
this.targetObject._touchedHandler(this);
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the Input Manager.
|
||||
* @method Phaser.Pointer#update
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
if (this.active)
|
||||
{
|
||||
if (this._holdSent === false && this.duration >= this.game.input.holdRate)
|
||||
{
|
||||
if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
|
||||
{
|
||||
this.game.input.onHold.dispatch(this);
|
||||
}
|
||||
|
||||
this._holdSent = true;
|
||||
}
|
||||
|
||||
// Update the droppings history
|
||||
if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop)
|
||||
{
|
||||
this._nextDrop = this.game.time.now + this.game.input.recordRate;
|
||||
|
||||
this._history.push({
|
||||
x: this.position.x,
|
||||
y: this.position.y
|
||||
});
|
||||
|
||||
if (this._history.length > this.game.input.recordLimit)
|
||||
{
|
||||
this._history.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the Pointer is moved.
|
||||
* @method Phaser.Pointer#move
|
||||
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
|
||||
* @param {boolean} [fromClick=false] - Was this called from the click event?
|
||||
*/
|
||||
move: function (event, fromClick) {
|
||||
|
||||
if (this.game.input.pollLocked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof fromClick === 'undefined') { fromClick = false; }
|
||||
|
||||
if (typeof event.button !== 'undefined')
|
||||
{
|
||||
this.button = event.button;
|
||||
}
|
||||
|
||||
this.clientX = event.clientX;
|
||||
this.clientY = event.clientY;
|
||||
|
||||
this.pageX = event.pageX;
|
||||
this.pageY = event.pageY;
|
||||
|
||||
this.screenX = event.screenX;
|
||||
this.screenY = event.screenY;
|
||||
|
||||
if (this.isMouse && this.game.input.mouse.locked && !fromClick)
|
||||
{
|
||||
this.rawMovementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
|
||||
this.rawMovementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
|
||||
|
||||
this.movementX += this.rawMovementX;
|
||||
this.movementY += this.rawMovementY;
|
||||
}
|
||||
|
||||
this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x;
|
||||
this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y;
|
||||
|
||||
this.position.setTo(this.x, this.y);
|
||||
this.circle.x = this.x;
|
||||
this.circle.y = this.y;
|
||||
|
||||
if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
|
||||
{
|
||||
this.game.input.activePointer = this;
|
||||
this.game.input.x = this.x;
|
||||
this.game.input.y = this.y;
|
||||
this.game.input.position.setTo(this.game.input.x, this.game.input.y);
|
||||
this.game.input.circle.x = this.game.input.x;
|
||||
this.game.input.circle.y = this.game.input.y;
|
||||
}
|
||||
|
||||
this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY);
|
||||
|
||||
// If the game is paused we don't process any target objects or callbacks
|
||||
if (this.game.paused)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
// DEPRECATED - Soon to be removed
|
||||
if (this.game.input.moveCallback)
|
||||
{
|
||||
this.game.input.moveCallback.call(this.game.input.moveCallbackContext, this, this.x, this.y);
|
||||
}
|
||||
|
||||
var i = this.game.input.moveCallbacks.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
this.game.input.moveCallbacks[i].callback.call(this.game.input.moveCallbacks[i].context, this, this.x, this.y);
|
||||
}
|
||||
|
||||
// Easy out if we're dragging something and it still exists
|
||||
if (this.targetObject !== null && this.targetObject.isDragged === true)
|
||||
{
|
||||
if (this.targetObject.update(this) === false)
|
||||
{
|
||||
this.targetObject = null;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
// Work out which object is on the top
|
||||
this._highestRenderOrderID = Number.MAX_SAFE_INTEGER;
|
||||
this._highestRenderObject = null;
|
||||
this._highestInputPriorityID = -1;
|
||||
|
||||
// Run through the list
|
||||
if (this.game.input.interactiveItems.total > 0)
|
||||
{
|
||||
var currentNode = this.game.input.interactiveItems.first;
|
||||
|
||||
do
|
||||
{
|
||||
// If the object is using pixelPerfect checks, or has a higher InputManager.PriorityID OR if the priority ID is the same as the current highest AND it has a higher renderOrderID, then set it to the top
|
||||
if (currentNode && currentNode.validForInput(this._highestInputPriorityID, this._highestRenderOrderID))
|
||||
{
|
||||
if ((!fromClick && currentNode.checkPointerOver(this)) || (fromClick && currentNode.checkPointerDown(this)))
|
||||
{
|
||||
this._highestRenderOrderID = currentNode.sprite._cache[3]; // renderOrderID
|
||||
this._highestInputPriorityID = currentNode.priorityID;
|
||||
this._highestRenderObject = currentNode;
|
||||
}
|
||||
}
|
||||
currentNode = this.game.input.interactiveItems.next;
|
||||
}
|
||||
while (currentNode !== null);
|
||||
}
|
||||
|
||||
if (this._highestRenderObject === null)
|
||||
{
|
||||
// The pointer isn't currently over anything, check if we've got a lingering previous target
|
||||
if (this.targetObject)
|
||||
{
|
||||
// console.log("The pointer isn't currently over anything, check if we've got a lingering previous target");
|
||||
this.targetObject._pointerOutHandler(this);
|
||||
this.targetObject = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.targetObject === null)
|
||||
{
|
||||
// And now set the new one
|
||||
// console.log('And now set the new one');
|
||||
this.targetObject = this._highestRenderObject;
|
||||
this._highestRenderObject._pointerOverHandler(this);
|
||||
}
|
||||
else
|
||||
{
|
||||
// We've got a target from the last update
|
||||
// console.log("We've got a target from the last update");
|
||||
if (this.targetObject === this._highestRenderObject)
|
||||
{
|
||||
// Same target as before, so update it
|
||||
// console.log("Same target as before, so update it");
|
||||
if (this._highestRenderObject.update(this) === false)
|
||||
{
|
||||
this.targetObject = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The target has changed, so tell the old one we've left it
|
||||
// console.log("The target has changed, so tell the old one we've left it");
|
||||
this.targetObject._pointerOutHandler(this);
|
||||
|
||||
// And now set the new one
|
||||
this.targetObject = this._highestRenderObject;
|
||||
this.targetObject._pointerOverHandler(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the Pointer leaves the target area.
|
||||
*
|
||||
* @method Phaser.Pointer#leave
|
||||
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
|
||||
*/
|
||||
leave: function (event) {
|
||||
|
||||
this.withinGame = false;
|
||||
this.move(event, false);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called when the Pointer leaves the touchscreen.
|
||||
*
|
||||
* @method Phaser.Pointer#stop
|
||||
* @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
|
||||
*/
|
||||
stop: function (event) {
|
||||
|
||||
if (this._stateReset)
|
||||
{
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
this.timeUp = this.game.time.now;
|
||||
|
||||
if (this.game.input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers === 0))
|
||||
{
|
||||
this.game.input.onUp.dispatch(this, event);
|
||||
|
||||
// Was it a tap?
|
||||
if (this.duration >= 0 && this.duration <= this.game.input.tapRate)
|
||||
{
|
||||
// Was it a double-tap?
|
||||
if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate)
|
||||
{
|
||||
// Yes, let's dispatch the signal then with the 2nd parameter set to true
|
||||
this.game.input.onTap.dispatch(this, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Wasn't a double-tap, so dispatch a single tap signal
|
||||
this.game.input.onTap.dispatch(this, false);
|
||||
}
|
||||
|
||||
this.previousTapTime = this.timeUp;
|
||||
}
|
||||
}
|
||||
|
||||
// Mouse is always active
|
||||
if (this.id > 0)
|
||||
{
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
this.withinGame = false;
|
||||
this.isDown = false;
|
||||
this.isUp = true;
|
||||
this.pointerId = null;
|
||||
this.identifier = null;
|
||||
|
||||
this.positionUp.setTo(this.x, this.y);
|
||||
|
||||
if (this.isMouse === false)
|
||||
{
|
||||
this.game.input.currentPointers--;
|
||||
}
|
||||
|
||||
this.game.input.interactiveItems.callAll('_releasedHandler', this);
|
||||
|
||||
this.targetObject = null;
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
|
||||
* Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
|
||||
* If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
|
||||
* @method Phaser.Pointer#justPressed
|
||||
* @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
|
||||
* @return {boolean} true if the Pointer was pressed down within the duration given.
|
||||
*/
|
||||
justPressed: function (duration) {
|
||||
|
||||
duration = duration || this.game.input.justPressedRate;
|
||||
|
||||
return (this.isDown === true && (this.timeDown + duration) > this.game.time.now);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
|
||||
* Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
|
||||
* If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
|
||||
* @method Phaser.Pointer#justReleased
|
||||
* @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
|
||||
* @return {boolean} true if the Pointer was released within the duration given.
|
||||
*/
|
||||
justReleased: function (duration) {
|
||||
|
||||
duration = duration || this.game.input.justReleasedRate;
|
||||
|
||||
return (this.isUp === true && (this.timeUp + duration) > this.game.time.now);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
|
||||
* @method Phaser.Pointer#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
if (this.isMouse === false)
|
||||
{
|
||||
this.active = false;
|
||||
}
|
||||
|
||||
this.pointerId = null;
|
||||
this.identifier = null;
|
||||
this.isDown = false;
|
||||
this.isUp = true;
|
||||
this.totalTouches = 0;
|
||||
this._holdSent = false;
|
||||
this._history.length = 0;
|
||||
this._stateReset = true;
|
||||
|
||||
if (this.targetObject)
|
||||
{
|
||||
this.targetObject._releasedHandler(this);
|
||||
}
|
||||
|
||||
this.targetObject = null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets the movementX and movementY properties. Use in your update handler after retrieving the values.
|
||||
* @method Phaser.Pointer#resetMovement
|
||||
*/
|
||||
resetMovement: function() {
|
||||
|
||||
this.movementX = 0;
|
||||
this.movementY = 0;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Pointer.prototype.constructor = Phaser.Pointer;
|
||||
|
||||
/**
|
||||
* How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
|
||||
* @name Phaser.Pointer#duration
|
||||
* @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Pointer.prototype, "duration", {
|
||||
|
||||
get: function () {
|
||||
|
||||
if (this.isUp)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
return this.game.time.now - this.timeDown;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gets the X value of this Pointer in world coordinates based on the world camera.
|
||||
* @name Phaser.Pointer#worldX
|
||||
* @property {number} duration - The X value of this Pointer in world coordinates based on the world camera.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.game.world.camera.x + this.x;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gets the Y value of this Pointer in world coordinates based on the world camera.
|
||||
* @name Phaser.Pointer#worldY
|
||||
* @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.game.world.camera.y + this.y;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
569
src/input/SinglePad.js
Normal file
569
src/input/SinglePad.js
Normal file
@@ -0,0 +1,569 @@
|
||||
/**
|
||||
* @author @karlmacklin <tacklemcclean@gmail.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Phaser.SinglePad
|
||||
* @classdesc A single Phaser Gamepad
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {Object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
|
||||
*/
|
||||
Phaser.SinglePad = function (game, padParent) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
|
||||
*/
|
||||
this._padParent = padParent;
|
||||
|
||||
/**
|
||||
* @property {number} index - The gamepad index as per browsers data
|
||||
* @default
|
||||
*/
|
||||
this._index = null;
|
||||
|
||||
/**
|
||||
* @property {Object} _rawPad - The 'raw' gamepad data.
|
||||
* @private
|
||||
*/
|
||||
this._rawPad = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} _connected - Is this pad connected or not.
|
||||
* @private
|
||||
*/
|
||||
this._connected = false;
|
||||
|
||||
/**
|
||||
* @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
|
||||
* @private
|
||||
*/
|
||||
this._prevTimestamp = null;
|
||||
|
||||
/**
|
||||
* @property {Array} _rawButtons - The 'raw' button state.
|
||||
* @private
|
||||
*/
|
||||
this._rawButtons = [];
|
||||
|
||||
/**
|
||||
* @property {Array} _buttons - Current Phaser state of the buttons.
|
||||
* @private
|
||||
*/
|
||||
this._buttons = [];
|
||||
|
||||
/**
|
||||
* @property {Array} _axes - Current axes state.
|
||||
* @private
|
||||
*/
|
||||
this._axes = [];
|
||||
|
||||
/**
|
||||
* @property {Array} _hotkeys - Hotkey buttons.
|
||||
* @private
|
||||
*/
|
||||
this._hotkeys = [];
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which the callbacks are run.
|
||||
*/
|
||||
this.callbackContext = this;
|
||||
|
||||
/**
|
||||
* @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
|
||||
*/
|
||||
this.onConnectCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
|
||||
*/
|
||||
this.onDisconnectCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
|
||||
*/
|
||||
this.onDownCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
|
||||
*/
|
||||
this.onUpCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
|
||||
*/
|
||||
this.onAxisCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
|
||||
*/
|
||||
this.onFloatCallback = null;
|
||||
|
||||
/**
|
||||
* @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
|
||||
*/
|
||||
this.deadZone = 0.26;
|
||||
|
||||
};
|
||||
|
||||
Phaser.SinglePad.prototype = {
|
||||
|
||||
/**
|
||||
* Add callbacks to the this Gamepad to handle connect/disconnect/button down/button up/axis change/float value buttons
|
||||
* @method Phaser.SinglePad#addCallbacks
|
||||
* @param {Object} context - The context under which the callbacks are run.
|
||||
* @param {Object} callbacks - Object that takes six different callbak methods:
|
||||
* onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
|
||||
*/
|
||||
addCallbacks: function (context, callbacks) {
|
||||
|
||||
if (typeof callbacks !== 'undefined')
|
||||
{
|
||||
this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
|
||||
this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
|
||||
this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
|
||||
this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
|
||||
this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
|
||||
this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
|
||||
* The Key object can then be polled, have events attached to it, etc.
|
||||
*
|
||||
* @method Phaser.SinglePad#addButton
|
||||
* @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0 or Phaser.Gamepad.BUTTON_1
|
||||
* @return {Phaser.GamepadButton} The GamepadButton object which you can store locally and reference directly.
|
||||
*/
|
||||
addButton: function (buttonCode) {
|
||||
|
||||
this._hotkeys[buttonCode] = new Phaser.GamepadButton(this.game, buttonCode);
|
||||
return this._hotkeys[buttonCode];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Main update function, should be called by Phaser.Gamepad
|
||||
* @method Phaser.SinglePad#pollStatus
|
||||
*/
|
||||
pollStatus: function () {
|
||||
|
||||
if (this._rawPad.timestamp && (this._rawPad.timestamp == this._prevTimestamp))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0; i < this._rawPad.buttons.length; i += 1)
|
||||
{
|
||||
var buttonValue = this._rawPad.buttons[i];
|
||||
|
||||
if (this._rawButtons[i] !== buttonValue)
|
||||
{
|
||||
if (buttonValue === 1)
|
||||
{
|
||||
this.processButtonDown(i, buttonValue);
|
||||
}
|
||||
else if (buttonValue === 0)
|
||||
{
|
||||
this.processButtonUp(i, buttonValue);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.processButtonFloat(i, buttonValue);
|
||||
}
|
||||
|
||||
this._rawButtons[i] = buttonValue;
|
||||
}
|
||||
}
|
||||
|
||||
var axes = this._rawPad.axes;
|
||||
|
||||
for (var j = 0; j < axes.length; j += 1)
|
||||
{
|
||||
var axis = axes[j];
|
||||
|
||||
if (axis > 0 && axis > this.deadZone || axis < 0 && axis < -this.deadZone)
|
||||
{
|
||||
this.processAxisChange({axis: j, value: axis});
|
||||
}
|
||||
else
|
||||
{
|
||||
this.processAxisChange({axis: j, value: 0});
|
||||
}
|
||||
}
|
||||
|
||||
this._prevTimestamp = this._rawPad.timestamp;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Gamepad connect function, should be called by Phaser.Gamepad
|
||||
* @method Phaser.SinglePad#connect
|
||||
* @param {Object} rawPad - The raw gamepad object
|
||||
*/
|
||||
connect: function (rawPad) {
|
||||
|
||||
var triggerCallback = !this._connected;
|
||||
|
||||
this._index = rawPad.index;
|
||||
this._connected = true;
|
||||
this._rawPad = rawPad;
|
||||
this._rawButtons = rawPad.buttons;
|
||||
this._axes = rawPad.axes;
|
||||
|
||||
if (triggerCallback && this._padParent.onConnectCallback)
|
||||
{
|
||||
this._padParent.onConnectCallback.call(this._padParent.callbackContext, this._index);
|
||||
}
|
||||
|
||||
if (triggerCallback && this.onConnectCallback)
|
||||
{
|
||||
this.onConnectCallback.call(this.callbackContext);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Gamepad disconnect function, should be called by Phaser.Gamepad
|
||||
* @method Phaser.SinglePad#disconnect
|
||||
*/
|
||||
disconnect: function () {
|
||||
|
||||
var triggerCallback = this._connected;
|
||||
this._connected = false;
|
||||
this._rawPad = undefined;
|
||||
this._rawButtons = [];
|
||||
this._buttons = [];
|
||||
var disconnectingIndex = this._index;
|
||||
this._index = null;
|
||||
|
||||
if (triggerCallback && this._padParent.onDisconnectCallback)
|
||||
{
|
||||
this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
|
||||
}
|
||||
|
||||
if (triggerCallback && this.onDisconnectCallback)
|
||||
{
|
||||
this.onDisconnectCallback.call(this.callbackContext);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles changes in axis
|
||||
* @method Phaser.SinglePad#processAxisChange
|
||||
* @param {Object} axisState - State of the relevant axis
|
||||
*/
|
||||
processAxisChange: function (axisState) {
|
||||
|
||||
if (this.game.input.disabled || this.game.input.gamepad.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._axes[axisState.axis] === axisState.value)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._axes[axisState.axis] = axisState.value;
|
||||
|
||||
if (this._padParent.onAxisCallback)
|
||||
{
|
||||
this._padParent.onAxisCallback.call(this._padParent.callbackContext, axisState, this._index);
|
||||
}
|
||||
|
||||
if (this.onAxisCallback)
|
||||
{
|
||||
this.onAxisCallback.call(this.callbackContext, axisState);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles button down press
|
||||
* @method Phaser.SinglePad#processButtonDown
|
||||
* @param {number} buttonCode - Which buttonCode of this button
|
||||
* @param {Object} value - Button value
|
||||
*/
|
||||
processButtonDown: function (buttonCode, value) {
|
||||
|
||||
if (this.game.input.disabled || this.game.input.gamepad.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._padParent.onDownCallback)
|
||||
{
|
||||
this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
|
||||
}
|
||||
|
||||
if (this.onDownCallback)
|
||||
{
|
||||
this.onDownCallback.call(this.callbackContext, buttonCode, value);
|
||||
}
|
||||
|
||||
if (this._buttons[buttonCode] && this._buttons[buttonCode].isDown)
|
||||
{
|
||||
// Key already down and still down, so update
|
||||
this._buttons[buttonCode].duration = this.game.time.now - this._buttons[buttonCode].timeDown;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!this._buttons[buttonCode])
|
||||
{
|
||||
// Not used this button before, so register it
|
||||
this._buttons[buttonCode] = {
|
||||
isDown: true,
|
||||
timeDown: this.game.time.now,
|
||||
timeUp: 0,
|
||||
duration: 0,
|
||||
value: value
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
// Button used before but freshly down
|
||||
this._buttons[buttonCode].isDown = true;
|
||||
this._buttons[buttonCode].timeDown = this.game.time.now;
|
||||
this._buttons[buttonCode].duration = 0;
|
||||
this._buttons[buttonCode].value = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._hotkeys[buttonCode])
|
||||
{
|
||||
this._hotkeys[buttonCode].processButtonDown(value);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles button release
|
||||
* @method Phaser.SinglePad#processButtonUp
|
||||
* @param {number} buttonCode - Which buttonCode of this button
|
||||
* @param {Object} value - Button value
|
||||
*/
|
||||
processButtonUp: function (buttonCode, value) {
|
||||
|
||||
if (this.game.input.disabled || this.game.input.gamepad.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._padParent.onUpCallback)
|
||||
{
|
||||
this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
|
||||
}
|
||||
|
||||
if (this.onUpCallback)
|
||||
{
|
||||
this.onUpCallback.call(this.callbackContext, buttonCode, value);
|
||||
}
|
||||
|
||||
if (this._hotkeys[buttonCode])
|
||||
{
|
||||
this._hotkeys[buttonCode].processButtonUp(value);
|
||||
}
|
||||
|
||||
if (this._buttons[buttonCode])
|
||||
{
|
||||
this._buttons[buttonCode].isDown = false;
|
||||
this._buttons[buttonCode].timeUp = this.game.time.now;
|
||||
this._buttons[buttonCode].value = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Not used this button before, so register it
|
||||
this._buttons[buttonCode] = {
|
||||
isDown: false,
|
||||
timeDown: this.game.time.now,
|
||||
timeUp: this.game.time.now,
|
||||
duration: 0,
|
||||
value: value
|
||||
};
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
|
||||
* @method Phaser.SinglePad#processButtonFloat
|
||||
* @param {number} buttonCode - Which buttonCode of this button
|
||||
* @param {Object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
|
||||
*/
|
||||
processButtonFloat: function (buttonCode, value) {
|
||||
|
||||
if (this.game.input.disabled || this.game.input.gamepad.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._padParent.onFloatCallback)
|
||||
{
|
||||
this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this._index);
|
||||
}
|
||||
|
||||
if (this.onFloatCallback)
|
||||
{
|
||||
this.onFloatCallback.call(this.callbackContext, buttonCode, value);
|
||||
}
|
||||
|
||||
if (!this._buttons[buttonCode])
|
||||
{
|
||||
// Not used this button before, so register it
|
||||
this._buttons[buttonCode] = { value: value };
|
||||
}
|
||||
else
|
||||
{
|
||||
// Button used before but freshly down
|
||||
this._buttons[buttonCode].value = value;
|
||||
}
|
||||
|
||||
if (this._hotkeys[buttonCode])
|
||||
{
|
||||
this._hotkeys[buttonCode].processButtonFloat(value);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns value of requested axis
|
||||
* @method Phaser.SinglePad#axis
|
||||
* @param {number} axisCode - The index of the axis to check
|
||||
* @return {number} Axis value if available otherwise false
|
||||
*/
|
||||
axis: function (axisCode) {
|
||||
|
||||
if (this._axes[axisCode])
|
||||
{
|
||||
return this._axes[axisCode];
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the button is currently pressed down.
|
||||
* @method Phaser.SinglePad#isDown
|
||||
* @param {number} buttonCode - The buttonCode of the key to check.
|
||||
* @return {boolean} True if the key is currently down.
|
||||
*/
|
||||
isDown: function (buttonCode) {
|
||||
|
||||
if (this._buttons[buttonCode])
|
||||
{
|
||||
return this._buttons[buttonCode].isDown;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms).
|
||||
* @method Phaser.SinglePad#justReleased
|
||||
* @param {number} buttonCode - The buttonCode of the button to check for.
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just released.
|
||||
* @return {boolean} True if the button is just released otherwise false.
|
||||
*/
|
||||
justReleased: function (buttonCode, duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 250; }
|
||||
|
||||
return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown === false && (this.game.time.now - this._buttons[buttonCode].timeUp < duration));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
|
||||
* @method Phaser.SinglePad#justPressed
|
||||
* @param {number} buttonCode - The buttonCode of the button to check for.
|
||||
* @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
|
||||
* @return {boolean} True if the button is just pressed otherwise false.
|
||||
*/
|
||||
justPressed: function (buttonCode, duration) {
|
||||
|
||||
if (typeof duration === "undefined") { duration = 250; }
|
||||
|
||||
return (this._buttons[buttonCode] && this._buttons[buttonCode].isDown && this._buttons[buttonCode].duration < duration);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
|
||||
* analog trigger buttons on the XBOX 360 controller
|
||||
* @method Phaser.SinglePad#buttonValue
|
||||
* @param {number} buttonCode - The buttonCode of the button to check.
|
||||
* @return {boolean} Button value if available otherwise false.
|
||||
*/
|
||||
buttonValue: function (buttonCode) {
|
||||
|
||||
if (this._buttons[buttonCode])
|
||||
{
|
||||
return this._buttons[buttonCode].value;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset all buttons/axes of this gamepad
|
||||
* @method Phaser.SinglePad#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
for (var i = 0; i < this._buttons.length; i++)
|
||||
{
|
||||
this._buttons[i] = 0;
|
||||
}
|
||||
|
||||
for (var j = 0; j < this._axes.length; j++)
|
||||
{
|
||||
this._axes[j] = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
|
||||
|
||||
/**
|
||||
* Whether or not this particular gamepad is connected or not.
|
||||
* @name Phaser.SinglePad#connected
|
||||
* @property {boolean} connected - Whether or not this particular gamepad is connected or not.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.SinglePad.prototype, "connected", {
|
||||
|
||||
get: function () {
|
||||
return this._connected;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Gamepad index as per browser data
|
||||
* @name Phaser.SinglePad#index
|
||||
* @property {number} index - The gamepad index, used to identify specific gamepads in the browser
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.SinglePad.prototype, "index", {
|
||||
|
||||
get: function () {
|
||||
return this._index;
|
||||
}
|
||||
|
||||
});
|
||||
379
src/input/Touch.js
Normal file
379
src/input/Touch.js
Normal file
@@ -0,0 +1,379 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
|
||||
*
|
||||
* @class Phaser.Touch
|
||||
* @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects.
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Touch = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {boolean} disabled - You can disable all Touch events by setting disabled = true. While set all new touch events will be ignored.
|
||||
* @return {boolean}
|
||||
*/
|
||||
this.disabled = false;
|
||||
|
||||
/**
|
||||
* @property {Object} callbackContext - The context under which callbacks are called.
|
||||
*/
|
||||
this.callbackContext = this.game;
|
||||
|
||||
/**
|
||||
* @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
|
||||
*/
|
||||
this.touchStartCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
|
||||
*/
|
||||
this.touchMoveCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
|
||||
*/
|
||||
this.touchEndCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
|
||||
*/
|
||||
this.touchEnterCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
|
||||
*/
|
||||
this.touchLeaveCallback = null;
|
||||
|
||||
/**
|
||||
* @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
|
||||
*/
|
||||
this.touchCancelCallback = null;
|
||||
|
||||
/**
|
||||
* @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
|
||||
* @default
|
||||
*/
|
||||
this.preventDefault = true;
|
||||
|
||||
/**
|
||||
* @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
|
||||
* @default
|
||||
*/
|
||||
this.event = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchStart - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchStart = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchMove - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchMove = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchEnd - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchEnd = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchEnter - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchEnter = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchLeave - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchLeave = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchCancel - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchCancel = null;
|
||||
|
||||
/**
|
||||
* @property {function} _onTouchMove - Internal event handler reference.
|
||||
* @private
|
||||
*/
|
||||
this._onTouchMove = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Touch.prototype = {
|
||||
|
||||
/**
|
||||
* Starts the event listeners running.
|
||||
* @method Phaser.Touch#start
|
||||
*/
|
||||
start: function () {
|
||||
|
||||
if (this._onTouchStart !== null)
|
||||
{
|
||||
// Avoid setting multiple listeners
|
||||
return;
|
||||
}
|
||||
|
||||
var _this = this;
|
||||
|
||||
if (this.game.device.touch)
|
||||
{
|
||||
this._onTouchStart = function (event) {
|
||||
return _this.onTouchStart(event);
|
||||
};
|
||||
|
||||
this._onTouchMove = function (event) {
|
||||
return _this.onTouchMove(event);
|
||||
};
|
||||
|
||||
this._onTouchEnd = function (event) {
|
||||
return _this.onTouchEnd(event);
|
||||
};
|
||||
|
||||
this._onTouchEnter = function (event) {
|
||||
return _this.onTouchEnter(event);
|
||||
};
|
||||
|
||||
this._onTouchLeave = function (event) {
|
||||
return _this.onTouchLeave(event);
|
||||
};
|
||||
|
||||
this._onTouchCancel = function (event) {
|
||||
return _this.onTouchCancel(event);
|
||||
};
|
||||
|
||||
this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
|
||||
this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
|
||||
this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
|
||||
this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
|
||||
this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
|
||||
this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Consumes all touchmove events on the document (only enable this if you know you need it!).
|
||||
* @method Phaser.Touch#consumeTouchMove
|
||||
*/
|
||||
consumeDocumentTouches: function () {
|
||||
|
||||
this._documentTouchMove = function (event) {
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
document.addEventListener('touchmove', this._documentTouchMove, false);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The internal method that handles the touchstart event from the browser.
|
||||
* @method Phaser.Touch#onTouchStart
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchStart: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchStartCallback)
|
||||
{
|
||||
this.touchStartCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
|
||||
// event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
|
||||
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
|
||||
for (var i = 0; i < event.changedTouches.length; i++)
|
||||
{
|
||||
this.game.input.startPointer(event.changedTouches[i]);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
|
||||
* Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
|
||||
* @method Phaser.Touch#onTouchCancel
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchCancel: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchCancelCallback)
|
||||
{
|
||||
this.touchCancelCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
|
||||
// http://www.w3.org/TR/touch-events/#dfn-touchcancel
|
||||
for (var i = 0; i < event.changedTouches.length; i++)
|
||||
{
|
||||
this.game.input.stopPointer(event.changedTouches[i]);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* For touch enter and leave its a list of the touch points that have entered or left the target.
|
||||
* Doesn't appear to be supported by most browsers on a canvas element yet.
|
||||
* @method Phaser.Touch#onTouchEnter
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchEnter: function (event) {
|
||||
|
||||
console.log('touch enter', event);
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchEnterCallback)
|
||||
{
|
||||
this.touchEnterCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.game.input.disabled || this.disabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* For touch enter and leave its a list of the touch points that have entered or left the target.
|
||||
* Doesn't appear to be supported by most browsers on a canvas element yet.
|
||||
* @method Phaser.Touch#onTouchLeave
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchLeave: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchLeaveCallback)
|
||||
{
|
||||
this.touchLeaveCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The handler for the touchmove events.
|
||||
* @method Phaser.Touch#onTouchMove
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchMove: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchMoveCallback)
|
||||
{
|
||||
this.touchMoveCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
for (var i = 0; i < event.changedTouches.length; i++)
|
||||
{
|
||||
this.game.input.updatePointer(event.changedTouches[i]);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The handler for the touchend events.
|
||||
* @method Phaser.Touch#onTouchEnd
|
||||
* @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
|
||||
*/
|
||||
onTouchEnd: function (event) {
|
||||
|
||||
this.event = event;
|
||||
|
||||
if (this.touchEndCallback)
|
||||
{
|
||||
this.touchEndCallback.call(this.callbackContext, event);
|
||||
}
|
||||
|
||||
if (this.preventDefault)
|
||||
{
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
// For touch end its a list of the touch points that have been removed from the surface
|
||||
// https://developer.mozilla.org/en-US/docs/DOM/TouchList
|
||||
// event.changedTouches = the touches that CHANGED in this event, not the total number of them
|
||||
for (var i = 0; i < event.changedTouches.length; i++)
|
||||
{
|
||||
this.game.input.stopPointer(event.changedTouches[i]);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop the event listeners.
|
||||
* @method Phaser.Touch#stop
|
||||
*/
|
||||
stop: function () {
|
||||
|
||||
if (this.game.device.touch)
|
||||
{
|
||||
this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
|
||||
this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
|
||||
this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
|
||||
this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
|
||||
this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
|
||||
this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Touch.prototype.constructor = Phaser.Touch;
|
||||
1368
src/loader/Cache.js
Normal file
1368
src/loader/Cache.js
Normal file
File diff suppressed because it is too large
Load Diff
1517
src/loader/Loader.js
Normal file
1517
src/loader/Loader.js
Normal file
File diff suppressed because it is too large
Load Diff
70
src/loader/LoaderParser.js
Normal file
70
src/loader/LoaderParser.js
Normal file
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
|
||||
*
|
||||
* @class Phaser.LoaderParser
|
||||
*/
|
||||
Phaser.LoaderParser = {
|
||||
|
||||
/**
|
||||
* Parse a Bitmap Font from an XML file.
|
||||
* @method Phaser.LoaderParser.bitmapFont
|
||||
* @param {Phaser.Game} game - A reference to the current game.
|
||||
* @param {object} xml - XML data you want to parse.
|
||||
* @param {string} cacheKey - The key of the texture this font uses in the cache.
|
||||
*/
|
||||
bitmapFont: function (game, xml, cacheKey, xSpacing, ySpacing) {
|
||||
|
||||
var data = {};
|
||||
var info = xml.getElementsByTagName('info')[0];
|
||||
var common = xml.getElementsByTagName('common')[0];
|
||||
|
||||
data.font = info.getAttribute('face');
|
||||
data.size = parseInt(info.getAttribute('size'), 10);
|
||||
data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
|
||||
data.chars = {};
|
||||
|
||||
var letters = xml.getElementsByTagName('char');
|
||||
var texture = PIXI.TextureCache[cacheKey];
|
||||
|
||||
for (var i = 0; i < letters.length; i++)
|
||||
{
|
||||
var charCode = parseInt(letters[i].getAttribute('id'), 10);
|
||||
|
||||
var textureRect = new PIXI.Rectangle(
|
||||
parseInt(letters[i].getAttribute('x'), 10),
|
||||
parseInt(letters[i].getAttribute('y'), 10),
|
||||
parseInt(letters[i].getAttribute('width'), 10),
|
||||
parseInt(letters[i].getAttribute('height'), 10)
|
||||
);
|
||||
|
||||
data.chars[charCode] = {
|
||||
xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
|
||||
yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
|
||||
xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
|
||||
kerning: {},
|
||||
texture: PIXI.TextureCache[cacheKey] = new PIXI.Texture(texture, textureRect)
|
||||
};
|
||||
}
|
||||
|
||||
var kernings = xml.getElementsByTagName('kerning');
|
||||
|
||||
for (i = 0; i < kernings.length; i++)
|
||||
{
|
||||
var first = parseInt(kernings[i].getAttribute('first'), 10);
|
||||
var second = parseInt(kernings[i].getAttribute('second'), 10);
|
||||
var amount = parseInt(kernings[i].getAttribute('amount'), 10);
|
||||
|
||||
data.chars[second].kerning[first] = amount;
|
||||
}
|
||||
|
||||
PIXI.BitmapText.fonts[cacheKey] = data;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
1367
src/math/Math.js
Normal file
1367
src/math/Math.js
Normal file
File diff suppressed because it is too large
Load Diff
355
src/math/QuadTree.js
Normal file
355
src/math/QuadTree.js
Normal file
@@ -0,0 +1,355 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Javascript QuadTree
|
||||
* @version 1.0
|
||||
* @author Timo Hausmann
|
||||
*
|
||||
* @version 1.3, March 11th 2014
|
||||
* @author Richard Davey
|
||||
* The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
|
||||
* it massively to add node indexing, removed lots of temp. var creation and significantly
|
||||
* increased performance as a result.
|
||||
*
|
||||
* Original version at https://github.com/timohausmann/quadtree-js/
|
||||
*/
|
||||
|
||||
/**
|
||||
* @copyright © 2012 Timo Hausmann
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
* "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish,
|
||||
* distribute, sublicense, and/or sell copies of the Software, and to
|
||||
* permit persons to whom the Software is furnished to do so, subject to
|
||||
* the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be
|
||||
* included in all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
/**
|
||||
* QuadTree Constructor
|
||||
*
|
||||
* @class Phaser.QuadTree
|
||||
* @classdesc A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
|
||||
* However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
|
||||
* Original version at https://github.com/timohausmann/quadtree-js/
|
||||
* @constructor
|
||||
* @param {number} x - The top left coordinate of the quadtree.
|
||||
* @param {number} y - The top left coordinate of the quadtree.
|
||||
* @param {number} width - The width of the quadtree in pixels.
|
||||
* @param {number} height - The height of the quadtree in pixels.
|
||||
* @param {number} [maxObjects=10] - The maximum number of objects per node.
|
||||
* @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
|
||||
* @param {number} [level=0] - Which level is this?
|
||||
*/
|
||||
Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
|
||||
|
||||
/**
|
||||
* @property {number} maxObjects - The maximum number of objects per node.
|
||||
* @default
|
||||
*/
|
||||
this.maxObjects = 10;
|
||||
|
||||
/**
|
||||
* @property {number} maxLevels - The maximum number of levels to break down to.
|
||||
* @default
|
||||
*/
|
||||
this.maxLevels = 4;
|
||||
|
||||
/**
|
||||
* @property {number} level - The current level.
|
||||
*/
|
||||
this.level = 0;
|
||||
|
||||
/**
|
||||
* @property {object} bounds - Object that contains the quadtree bounds.
|
||||
*/
|
||||
this.bounds = {};
|
||||
|
||||
/**
|
||||
* @property {array} objects - Array of quadtree children.
|
||||
*/
|
||||
this.objects = [];
|
||||
|
||||
/**
|
||||
* @property {array} nodes - Array of associated child nodes.
|
||||
*/
|
||||
this.nodes = [];
|
||||
|
||||
/**
|
||||
* @property {array} _empty - Internal empty array.
|
||||
* @private
|
||||
*/
|
||||
this._empty = [];
|
||||
|
||||
this.reset(x, y, width, height, maxObjects, maxLevels, level);
|
||||
|
||||
};
|
||||
|
||||
Phaser.QuadTree.prototype = {
|
||||
|
||||
/**
|
||||
* Resets the QuadTree.
|
||||
*
|
||||
* @method Phaser.QuadTree#reset
|
||||
* @param {number} x - The top left coordinate of the quadtree.
|
||||
* @param {number} y - The top left coordinate of the quadtree.
|
||||
* @param {number} width - The width of the quadtree in pixels.
|
||||
* @param {number} height - The height of the quadtree in pixels.
|
||||
* @param {number} [maxObjects=10] - The maximum number of objects per node.
|
||||
* @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
|
||||
* @param {number} [level=0] - Which level is this?
|
||||
*/
|
||||
reset: function (x, y, width, height, maxObjects, maxLevels, level) {
|
||||
|
||||
this.maxObjects = maxObjects || 10;
|
||||
this.maxLevels = maxLevels || 4;
|
||||
this.level = level || 0;
|
||||
|
||||
this.bounds = {
|
||||
x: Math.round(x),
|
||||
y: Math.round(y),
|
||||
width: width,
|
||||
height: height,
|
||||
subWidth: Math.floor(width / 2),
|
||||
subHeight: Math.floor(height / 2),
|
||||
right: Math.round(x) + Math.floor(width / 2),
|
||||
bottom: Math.round(y) + Math.floor(height / 2)
|
||||
};
|
||||
|
||||
this.objects.length = 0;
|
||||
this.nodes.length = 0;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
|
||||
*
|
||||
* @method Phaser.QuadTree#populate
|
||||
* @param {Phaser.Group} group - The Group to add to the quadtree.
|
||||
*/
|
||||
populate: function (group) {
|
||||
|
||||
group.forEach(this.populateHandler, this, true);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Handler for the populate method.
|
||||
*
|
||||
* @method Phaser.QuadTree#populateHandler
|
||||
* @param {Phaser.Sprite|object} sprite - The Sprite to check.
|
||||
*/
|
||||
populateHandler: function (sprite) {
|
||||
|
||||
if (sprite.body && sprite.exists)
|
||||
{
|
||||
this.insert(sprite.body);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Split the node into 4 subnodes
|
||||
*
|
||||
* @method Phaser.QuadTree#split
|
||||
*/
|
||||
split: function () {
|
||||
|
||||
this.level++;
|
||||
|
||||
// top right node
|
||||
this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
|
||||
|
||||
// top left node
|
||||
this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
|
||||
|
||||
// bottom left node
|
||||
this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
|
||||
|
||||
// bottom right node
|
||||
this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
|
||||
*
|
||||
* @method Phaser.QuadTree#insert
|
||||
* @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties.
|
||||
*/
|
||||
insert: function (body) {
|
||||
|
||||
var i = 0;
|
||||
var index;
|
||||
|
||||
// if we have subnodes ...
|
||||
if (this.nodes[0] != null)
|
||||
{
|
||||
index = this.getIndex(body);
|
||||
|
||||
if (index !== -1)
|
||||
{
|
||||
this.nodes[index].insert(body);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.objects.push(body);
|
||||
|
||||
if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
|
||||
{
|
||||
// Split if we don't already have subnodes
|
||||
if (this.nodes[0] == null)
|
||||
{
|
||||
this.split();
|
||||
}
|
||||
|
||||
// Add objects to subnodes
|
||||
while (i < this.objects.length)
|
||||
{
|
||||
index = this.getIndex(this.objects[i]);
|
||||
|
||||
if (index !== -1)
|
||||
{
|
||||
// this is expensive - see what we can do about it
|
||||
this.nodes[index].insert(this.objects.splice(i, 1)[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Determine which node the object belongs to.
|
||||
*
|
||||
* @method Phaser.QuadTree#getIndex
|
||||
* @param {Phaser.Rectangle|object} rect - The bounds in which to check.
|
||||
* @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node.
|
||||
*/
|
||||
getIndex: function (rect) {
|
||||
|
||||
// default is that rect doesn't fit, i.e. it straddles the internal quadrants
|
||||
var index = -1;
|
||||
|
||||
if (rect.x < this.bounds.right && rect.right < this.bounds.right)
|
||||
{
|
||||
if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
|
||||
{
|
||||
// rect fits within the top-left quadrant of this quadtree
|
||||
index = 1;
|
||||
}
|
||||
else if (rect.y > this.bounds.bottom)
|
||||
{
|
||||
// rect fits within the bottom-left quadrant of this quadtree
|
||||
index = 2;
|
||||
}
|
||||
}
|
||||
else if (rect.x > this.bounds.right)
|
||||
{
|
||||
// rect can completely fit within the right quadrants
|
||||
if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
|
||||
{
|
||||
// rect fits within the top-right quadrant of this quadtree
|
||||
index = 0;
|
||||
}
|
||||
else if (rect.y > this.bounds.bottom)
|
||||
{
|
||||
// rect fits within the bottom-right quadrant of this quadtree
|
||||
index = 3;
|
||||
}
|
||||
}
|
||||
|
||||
return index;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Return all objects that could collide with the given Sprite or Rectangle.
|
||||
*
|
||||
* @method Phaser.QuadTree#retrieve
|
||||
* @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle.
|
||||
* @return {array} - Array with all detected objects.
|
||||
*/
|
||||
retrieve: function (source) {
|
||||
|
||||
if (source instanceof Phaser.Rectangle)
|
||||
{
|
||||
var returnObjects = this.objects;
|
||||
|
||||
var index = this.getIndex(source);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!source.body)
|
||||
{
|
||||
return this._empty;
|
||||
}
|
||||
|
||||
var returnObjects = this.objects;
|
||||
|
||||
var index = this.getIndex(source.body);
|
||||
}
|
||||
|
||||
if (this.nodes[0])
|
||||
{
|
||||
// If rect fits into a subnode ..
|
||||
if (index !== -1)
|
||||
{
|
||||
returnObjects = returnObjects.concat(this.nodes[index].retrieve(source));
|
||||
}
|
||||
else
|
||||
{
|
||||
// If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
|
||||
returnObjects = returnObjects.concat(this.nodes[0].retrieve(source));
|
||||
returnObjects = returnObjects.concat(this.nodes[1].retrieve(source));
|
||||
returnObjects = returnObjects.concat(this.nodes[2].retrieve(source));
|
||||
returnObjects = returnObjects.concat(this.nodes[3].retrieve(source));
|
||||
}
|
||||
}
|
||||
|
||||
return returnObjects;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear the quadtree.
|
||||
* @method Phaser.QuadTree#clear
|
||||
*/
|
||||
clear: function () {
|
||||
|
||||
this.objects.length = 0;
|
||||
|
||||
var i = this.nodes.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
this.nodes[i].clear();
|
||||
this.nodes.splice(i, 1);
|
||||
}
|
||||
|
||||
this.nodes.length = 0;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
|
||||
280
src/math/RandomDataGenerator.js
Normal file
280
src/math/RandomDataGenerator.js
Normal file
@@ -0,0 +1,280 @@
|
||||
/* jshint noempty: false */
|
||||
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.RandomDataGenerator constructor.
|
||||
*
|
||||
* @class Phaser.RandomDataGenerator
|
||||
* @classdesc An extremely useful repeatable random data generator. Access it via Phaser.Game.rnd
|
||||
* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
|
||||
* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
|
||||
*
|
||||
* @constructor
|
||||
* @param {array} seeds
|
||||
*/
|
||||
Phaser.RandomDataGenerator = function (seeds) {
|
||||
|
||||
if (typeof seeds === "undefined") { seeds = []; }
|
||||
|
||||
/**
|
||||
* @property {number} c - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.c = 1;
|
||||
|
||||
/**
|
||||
* @property {number} s0 - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.s0 = 0;
|
||||
|
||||
/**
|
||||
* @property {number} s1 - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.s1 = 0;
|
||||
|
||||
/**
|
||||
* @property {number} s2 - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.s2 = 0;
|
||||
|
||||
this.sow(seeds);
|
||||
|
||||
};
|
||||
|
||||
Phaser.RandomDataGenerator.prototype = {
|
||||
|
||||
/**
|
||||
* Private random helper.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#rnd
|
||||
* @private
|
||||
* @return {number}
|
||||
*/
|
||||
rnd: function () {
|
||||
|
||||
var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
|
||||
|
||||
this.c = t | 0;
|
||||
this.s0 = this.s1;
|
||||
this.s1 = this.s2;
|
||||
this.s2 = t - this.c;
|
||||
|
||||
return this.s2;
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset the seed of the random data generator.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#sow
|
||||
* @param {array} seeds
|
||||
*/
|
||||
sow: function (seeds) {
|
||||
|
||||
if (typeof seeds === "undefined") { seeds = []; }
|
||||
|
||||
this.s0 = this.hash(' ');
|
||||
this.s1 = this.hash(this.s0);
|
||||
this.s2 = this.hash(this.s1);
|
||||
this.c = 1;
|
||||
|
||||
var seed;
|
||||
|
||||
for (var i = 0; seed = seeds[i++]; )
|
||||
{
|
||||
this.s0 -= this.hash(seed);
|
||||
this.s0 += ~~(this.s0 < 0);
|
||||
this.s1 -= this.hash(seed);
|
||||
this.s1 += ~~(this.s1 < 0);
|
||||
this.s2 -= this.hash(seed);
|
||||
this.s2 += ~~(this.s2 < 0);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method that creates a seed hash.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#hash
|
||||
* @private
|
||||
* @param {Any} data
|
||||
* @return {number} hashed value.
|
||||
*/
|
||||
hash: function (data) {
|
||||
|
||||
var h, i, n;
|
||||
n = 0xefc8249d;
|
||||
data = data.toString();
|
||||
|
||||
for (i = 0; i < data.length; i++) {
|
||||
n += data.charCodeAt(i);
|
||||
h = 0.02519603282416938 * n;
|
||||
n = h >>> 0;
|
||||
h -= n;
|
||||
h *= n;
|
||||
n = h >>> 0;
|
||||
h -= n;
|
||||
n += h * 0x100000000;// 2^32
|
||||
}
|
||||
|
||||
return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random integer between 0 and 2^32.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#integer
|
||||
* @return {number} A random integer between 0 and 2^32.
|
||||
*/
|
||||
integer: function() {
|
||||
|
||||
return this.rnd.apply(this) * 0x100000000;// 2^32
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random real number between 0 and 1.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#frac
|
||||
* @return {number} A random real number between 0 and 1.
|
||||
*/
|
||||
frac: function() {
|
||||
|
||||
return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random real number between 0 and 2^32.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#real
|
||||
* @return {number} A random real number between 0 and 2^32.
|
||||
*/
|
||||
real: function() {
|
||||
|
||||
return this.integer() + this.frac();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random integer between and including min and max.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#integerInRange
|
||||
* @param {number} min - The minimum value in the range.
|
||||
* @param {number} max - The maximum value in the range.
|
||||
* @return {number} A random number between min and max.
|
||||
*/
|
||||
integerInRange: function (min, max) {
|
||||
|
||||
return Math.floor(this.realInRange(0, max - min + 1) + min);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random real number between min and max.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#realInRange
|
||||
* @param {number} min - The minimum value in the range.
|
||||
* @param {number} max - The maximum value in the range.
|
||||
* @return {number} A random number between min and max.
|
||||
*/
|
||||
realInRange: function (min, max) {
|
||||
|
||||
return this.frac() * (max - min) + min;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random real number between -1 and 1.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#normal
|
||||
* @return {number} A random real number between -1 and 1.
|
||||
*/
|
||||
normal: function () {
|
||||
|
||||
return 1 - 2 * this.frac();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#uuid
|
||||
* @return {string} A valid RFC4122 version4 ID hex string
|
||||
*/
|
||||
uuid: function () {
|
||||
|
||||
var a = '';
|
||||
var b = '';
|
||||
|
||||
for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
|
||||
{
|
||||
}
|
||||
|
||||
return b;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random member of `array`.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#pick
|
||||
* @param {Array} ary - An Array to pick a random member of.
|
||||
* @return {any} A random member of the array.
|
||||
*/
|
||||
pick: function (ary) {
|
||||
|
||||
return ary[this.integerInRange(0, ary.length - 1)];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random member of `array`, favoring the earlier entries.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#weightedPick
|
||||
* @param {Array} ary - An Array to pick a random member of.
|
||||
* @return {any} A random member of the array.
|
||||
*/
|
||||
weightedPick: function (ary) {
|
||||
|
||||
return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1))];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#timestamp
|
||||
* @param {number} min - The minimum value in the range.
|
||||
* @param {number} max - The maximum value in the range.
|
||||
* @return {number} A random timestamp between min and max.
|
||||
*/
|
||||
timestamp: function (min, max) {
|
||||
|
||||
return this.realInRange(min || 946684800000, max || 1577862000000);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns a random angle between -180 and 180.
|
||||
*
|
||||
* @method Phaser.RandomDataGenerator#angle
|
||||
* @return {number} A random number between -180 and 180.
|
||||
*/
|
||||
angle: function() {
|
||||
|
||||
return this.integerInRange(-180, 180);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
|
||||
166
src/net/Net.js
Normal file
166
src/net/Net.js
Normal file
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
|
||||
*
|
||||
* @class Phaser.Net
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Net = function (game) {
|
||||
|
||||
this.game = game;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Net.prototype = {
|
||||
|
||||
/**
|
||||
* Returns the hostname given by the browser.
|
||||
*
|
||||
* @method Phaser.Net#getHostName
|
||||
* @return {string}
|
||||
*/
|
||||
getHostName: function () {
|
||||
|
||||
if (window.location && window.location.hostname) {
|
||||
return window.location.hostname;
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Compares the given domain name against the hostname of the browser containing the game.
|
||||
* If the domain name is found it returns true.
|
||||
* You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
|
||||
* Do not include 'http://' at the start.
|
||||
*
|
||||
* @method Phaser.Net#checkDomainName
|
||||
* @param {string} domain
|
||||
* @return {boolean} true if the given domain fragment can be found in the window.location.hostname
|
||||
*/
|
||||
checkDomainName: function (domain) {
|
||||
return window.location.hostname.indexOf(domain) !== -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates a value on the Query String and returns it in full.
|
||||
* If the value doesn't already exist it is set.
|
||||
* If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string.
|
||||
* Optionally you can redirect to the new url, or just return it as a string.
|
||||
*
|
||||
* @method Phaser.Net#updateQueryString
|
||||
* @param {string} key - The querystring key to update.
|
||||
* @param {string} value - The new value to be set. If it already exists it will be replaced.
|
||||
* @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
|
||||
* @param {string} url - The URL to modify. If none is given it uses window.location.href.
|
||||
* @return {string} If redirect is false then the modified url and query string is returned.
|
||||
*/
|
||||
updateQueryString: function (key, value, redirect, url) {
|
||||
|
||||
if (typeof redirect === "undefined") { redirect = false; }
|
||||
if (typeof url === "undefined" || url === '') { url = window.location.href; }
|
||||
|
||||
var output = '';
|
||||
var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
|
||||
|
||||
if (re.test(url))
|
||||
{
|
||||
if (typeof value !== 'undefined' && value !== null)
|
||||
{
|
||||
output = url.replace(re, '$1' + key + "=" + value + '$2$3');
|
||||
}
|
||||
else
|
||||
{
|
||||
output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (typeof value !== 'undefined' && value !== null)
|
||||
{
|
||||
var separator = url.indexOf('?') !== -1 ? '&' : '?';
|
||||
var hash = url.split('#');
|
||||
url = hash[0] + separator + key + '=' + value;
|
||||
|
||||
if (hash[1]) {
|
||||
url += '#' + hash[1];
|
||||
}
|
||||
|
||||
output = url;
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
output = url;
|
||||
}
|
||||
}
|
||||
|
||||
if (redirect)
|
||||
{
|
||||
window.location.href = output;
|
||||
}
|
||||
else
|
||||
{
|
||||
return output;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the Query String as an object.
|
||||
* If you specify a parameter it will return just the value of that parameter, should it exist.
|
||||
*
|
||||
* @method Phaser.Net#getQueryString
|
||||
* @param {string} [parameter=''] - If specified this will return just the value for that key.
|
||||
* @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
|
||||
*/
|
||||
getQueryString: function (parameter) {
|
||||
|
||||
if (typeof parameter === "undefined") { parameter = ''; }
|
||||
|
||||
var output = {};
|
||||
var keyValues = location.search.substring(1).split('&');
|
||||
|
||||
for (var i in keyValues)
|
||||
{
|
||||
var key = keyValues[i].split('=');
|
||||
|
||||
if (key.length > 1)
|
||||
{
|
||||
if (parameter && parameter == this.decodeURI(key[0]))
|
||||
{
|
||||
return this.decodeURI(key[1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the Query String as an object.
|
||||
* If you specify a parameter it will return just the value of that parameter, should it exist.
|
||||
*
|
||||
* @method Phaser.Net#decodeURI
|
||||
* @param {string} value - The URI component to be decoded.
|
||||
* @return {string} The decoded value.
|
||||
*/
|
||||
decodeURI: function (value) {
|
||||
return decodeURIComponent(value.replace(/\+/g, " "));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Net.prototype.constructor = Phaser.Net;
|
||||
81
src/particles/Particles.js
Normal file
81
src/particles/Particles.js
Normal file
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
|
||||
*
|
||||
* @class Phaser.Particles
|
||||
* @classdesc Phaser Particles
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
*/
|
||||
Phaser.Particles = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - A reference to the currently running Game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {object} emitters - Internal emitters store.
|
||||
*/
|
||||
this.emitters = {};
|
||||
|
||||
/**
|
||||
* @property {number} ID -
|
||||
* @default
|
||||
*/
|
||||
this.ID = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Particles.prototype = {
|
||||
|
||||
/**
|
||||
* Adds a new Particle Emitter to the Particle Manager.
|
||||
* @method Phaser.Particles#add
|
||||
* @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
|
||||
* @return {Phaser.Emitter} The emitter that was added.
|
||||
*/
|
||||
add: function (emitter) {
|
||||
|
||||
this.emitters[emitter.name] = emitter;
|
||||
|
||||
return emitter;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes an existing Particle Emitter from the Particle Manager.
|
||||
* @method Phaser.Particles#remove
|
||||
* @param {Phaser.Emitter} emitter - The emitter to remove.
|
||||
*/
|
||||
remove: function (emitter) {
|
||||
|
||||
delete this.emitters[emitter.name];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Called by the core game loop. Updates all Emitters who have their exists value set to true.
|
||||
* @method Phaser.Particles#update
|
||||
* @protected
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
for (var key in this.emitters)
|
||||
{
|
||||
if (this.emitters[key].exists)
|
||||
{
|
||||
this.emitters[key].update();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Particles.prototype.constructor = Phaser.Particles;
|
||||
1
src/particles/arcade/ArcadeParticles.js
Normal file
1
src/particles/arcade/ArcadeParticles.js
Normal file
@@ -0,0 +1 @@
|
||||
Phaser.Particles.Arcade = {};
|
||||
779
src/particles/arcade/Emitter.js
Normal file
779
src/particles/arcade/Emitter.js
Normal file
@@ -0,0 +1,779 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Phaser - ArcadeEmitter
|
||||
*
|
||||
* @class Phaser.Particles.Arcade.Emitter
|
||||
* @classdesc Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
|
||||
* continuous effects like rain and fire. All it really does is launch Particle objects out
|
||||
* at set intervals, and fixes their positions and velocities accorindgly.
|
||||
* @constructor
|
||||
* @extends Phaser.Group
|
||||
* @param {Phaser.Game} game - Current game instance.
|
||||
* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
|
||||
* @param {number} [maxParticles=50] - The total number of particles in this emitter..
|
||||
*/
|
||||
|
||||
Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
|
||||
|
||||
/**
|
||||
* @property {number} maxParticles - The total number of particles in this emitter..
|
||||
* @default
|
||||
*/
|
||||
this.maxParticles = maxParticles || 50;
|
||||
|
||||
Phaser.Group.call(this, game);
|
||||
|
||||
/**
|
||||
* @property {string} name - A handy string name for this emitter. Can be set to anything.
|
||||
*/
|
||||
this.name = 'emitter' + this.game.particles.ID++;
|
||||
|
||||
/**
|
||||
* @property {number} type - Internal Phaser Type value.
|
||||
* @protected
|
||||
*/
|
||||
this.type = Phaser.EMITTER;
|
||||
|
||||
/**
|
||||
* @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box.
|
||||
* @default
|
||||
*/
|
||||
this.width = 1;
|
||||
|
||||
/**
|
||||
* @property {number} height - The height of the emitter. Particles can be randomly generated from anywhere within this box.
|
||||
* @default
|
||||
*/
|
||||
this.height = 1;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.minParticleSpeed = new Phaser.Point(-100, -100);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.maxParticleSpeed = new Phaser.Point(100, 100);
|
||||
|
||||
/**
|
||||
* @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX.
|
||||
* @default
|
||||
*/
|
||||
this.minParticleScale = 1;
|
||||
|
||||
/**
|
||||
* @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX.
|
||||
* @default
|
||||
*/
|
||||
this.maxParticleScale = 1;
|
||||
|
||||
/**
|
||||
* @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0.
|
||||
*/
|
||||
this.scaleData = null;
|
||||
|
||||
/**
|
||||
* @property {number} minRotation - The minimum possible angular velocity of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.minRotation = -360;
|
||||
|
||||
/**
|
||||
* @property {number} maxRotation - The maximum possible angular velocity of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.maxRotation = 360;
|
||||
|
||||
/**
|
||||
* @property {number} minParticleAlpha - The minimum possible alpha value of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.minParticleAlpha = 1;
|
||||
|
||||
/**
|
||||
* @property {number} maxParticleAlpha - The maximum possible alpha value of a particle.
|
||||
* @default
|
||||
*/
|
||||
this.maxParticleAlpha = 1;
|
||||
|
||||
/**
|
||||
* @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0.
|
||||
*/
|
||||
this.alphaData = null;
|
||||
|
||||
/**
|
||||
* @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
|
||||
* @default
|
||||
*/
|
||||
this.gravity = 100;
|
||||
|
||||
/**
|
||||
* @property {any} particleClass - For emitting your own particle class types. They must extend Phaser.Particle.
|
||||
* @default
|
||||
*/
|
||||
this.particleClass = Phaser.Particle;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter.
|
||||
*/
|
||||
this.particleDrag = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
|
||||
* @default
|
||||
*/
|
||||
this.angularDrag = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
|
||||
* @default
|
||||
*/
|
||||
this.frequency = 100;
|
||||
|
||||
/**
|
||||
* @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever.
|
||||
* @default
|
||||
*/
|
||||
this.lifespan = 2000;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
|
||||
*/
|
||||
this.bounce = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
|
||||
* @default
|
||||
*/
|
||||
this.on = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation)
|
||||
* @default
|
||||
*/
|
||||
this.particleAnchor = new Phaser.Point(0.5, 0.5);
|
||||
|
||||
/**
|
||||
* @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL)
|
||||
* @default
|
||||
*/
|
||||
this.blendMode = Phaser.blendModes.NORMAL;
|
||||
|
||||
/**
|
||||
* The point the particles are emitted from.
|
||||
* Emitter.x and Emitter.y control the containers location, which updates all current particles
|
||||
* Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
|
||||
* @property {number} emitX
|
||||
*/
|
||||
this.emitX = x;
|
||||
|
||||
/**
|
||||
* The point the particles are emitted from.
|
||||
* Emitter.x and Emitter.y control the containers location, which updates all current particles
|
||||
* Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
|
||||
* @property {number} emitY
|
||||
*/
|
||||
this.emitY = y;
|
||||
|
||||
/**
|
||||
* @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure.
|
||||
*/
|
||||
this.autoScale = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure.
|
||||
*/
|
||||
this.autoAlpha = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list.
|
||||
* @default
|
||||
*/
|
||||
this.particleBringToTop = false;
|
||||
|
||||
/**
|
||||
* @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list.
|
||||
* @default
|
||||
*/
|
||||
this.particleSendToBack = false;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} _minParticleScale - Internal particle scale var.
|
||||
* @private
|
||||
*/
|
||||
this._minParticleScale = new Phaser.Point(1, 1);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} _maxParticleScale - Internal particle scale var.
|
||||
* @private
|
||||
*/
|
||||
this._maxParticleScale = new Phaser.Point(1, 1);
|
||||
|
||||
/**
|
||||
* @property {number} _quantity - Internal helper for deciding how many particles to launch.
|
||||
* @private
|
||||
*/
|
||||
this._quantity = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
|
||||
* @private
|
||||
*/
|
||||
this._timer = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _counter - Internal counter for figuring out how many particles to launch.
|
||||
* @private
|
||||
*/
|
||||
this._counter = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
|
||||
* @private
|
||||
*/
|
||||
this._explode = true;
|
||||
|
||||
/**
|
||||
* @property {any} _frames - Internal helper for the particle frame.
|
||||
* @private
|
||||
*/
|
||||
this._frames = null;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
|
||||
Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
|
||||
|
||||
/**
|
||||
* Called automatically by the game loop, decides when to launch particles and when to "die".
|
||||
* @method Phaser.Particles.Arcade.Emitter#update
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.update = function () {
|
||||
|
||||
if (this.on)
|
||||
{
|
||||
if (this._explode)
|
||||
{
|
||||
this._counter = 0;
|
||||
|
||||
do
|
||||
{
|
||||
this.emitParticle();
|
||||
this._counter++;
|
||||
}
|
||||
while (this._counter < this._quantity);
|
||||
|
||||
this.on = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (this.game.time.now >= this._timer)
|
||||
{
|
||||
this.emitParticle();
|
||||
|
||||
this._counter++;
|
||||
|
||||
if (this._quantity > 0)
|
||||
{
|
||||
if (this._counter >= this._quantity)
|
||||
{
|
||||
this.on = false;
|
||||
}
|
||||
}
|
||||
|
||||
this._timer = this.game.time.now + this.frequency;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var i = this.children.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
if (this.children[i].exists)
|
||||
{
|
||||
this.children[i].update();
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This function generates a new set of particles for use by this emitter.
|
||||
* The particles are stored internally waiting to be emitted via Emitter.start.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#makeParticles
|
||||
* @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random.
|
||||
* @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random.
|
||||
* @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles.
|
||||
* @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true.
|
||||
* @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
|
||||
* @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
|
||||
|
||||
if (typeof frames === 'undefined') { frames = 0; }
|
||||
if (typeof quantity === 'undefined') { quantity = this.maxParticles; }
|
||||
if (typeof collide === 'undefined') { collide = false; }
|
||||
if (typeof collideWorldBounds === 'undefined') { collideWorldBounds = false; }
|
||||
|
||||
var particle;
|
||||
var i = 0;
|
||||
var rndKey = keys;
|
||||
var rndFrame = frames;
|
||||
this._frames = frames;
|
||||
|
||||
while (i < quantity)
|
||||
{
|
||||
if (Array.isArray(keys))
|
||||
{
|
||||
rndKey = this.game.rnd.pick(keys);
|
||||
}
|
||||
|
||||
if (Array.isArray(frames))
|
||||
{
|
||||
rndFrame = this.game.rnd.pick(frames);
|
||||
}
|
||||
|
||||
particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame);
|
||||
|
||||
this.game.physics.arcade.enable(particle, false);
|
||||
|
||||
if (collide)
|
||||
{
|
||||
particle.body.checkCollision.any = true;
|
||||
particle.body.checkCollision.none = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
particle.body.checkCollision.none = true;
|
||||
}
|
||||
|
||||
particle.body.collideWorldBounds = collideWorldBounds;
|
||||
|
||||
particle.exists = false;
|
||||
particle.visible = false;
|
||||
particle.anchor.copyFrom(this.particleAnchor);
|
||||
|
||||
this.add(particle);
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Call this function to turn off all the particles and the emitter.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#kill
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
|
||||
|
||||
this.on = false;
|
||||
this.alive = false;
|
||||
this.exists = false;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Handy for bringing game objects "back to life". Just sets alive and exists back to true.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#revive
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
|
||||
|
||||
this.alive = true;
|
||||
this.exists = true;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Call this function to start emitting particles.
|
||||
* @method Phaser.Particles.Arcade.Emitter#start
|
||||
* @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false).
|
||||
* @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
|
||||
* @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms.
|
||||
* @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles".
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity) {
|
||||
|
||||
if (typeof explode === 'undefined') { explode = true; }
|
||||
if (typeof lifespan === 'undefined') { lifespan = 0; }
|
||||
if (typeof frequency === 'undefined' || frequency === null) { frequency = 250; }
|
||||
if (typeof quantity === 'undefined') { quantity = 0; }
|
||||
|
||||
this.revive();
|
||||
|
||||
this.visible = true;
|
||||
this.on = true;
|
||||
|
||||
this._explode = explode;
|
||||
this.lifespan = lifespan;
|
||||
this.frequency = frequency;
|
||||
|
||||
if (explode)
|
||||
{
|
||||
this._quantity = quantity;
|
||||
}
|
||||
else
|
||||
{
|
||||
this._quantity += quantity;
|
||||
}
|
||||
|
||||
this._counter = 0;
|
||||
this._timer = this.game.time.now + frequency;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* This function can be used both internally and externally to emit the next particle in the queue.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#emitParticle
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () {
|
||||
|
||||
var particle = this.getFirstExists(false);
|
||||
|
||||
if (particle === null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.width > 1 || this.height > 1)
|
||||
{
|
||||
particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom));
|
||||
}
|
||||
else
|
||||
{
|
||||
particle.reset(this.emitX, this.emitY);
|
||||
}
|
||||
|
||||
particle.angle = 0;
|
||||
particle.lifespan = this.lifespan;
|
||||
|
||||
if (this.particleBringToTop)
|
||||
{
|
||||
this.bringToTop(particle);
|
||||
}
|
||||
else if (this.particleSendToBack)
|
||||
{
|
||||
this.sendToBack(particle);
|
||||
}
|
||||
|
||||
if (this.autoScale)
|
||||
{
|
||||
particle.setScaleData(this.scaleData);
|
||||
}
|
||||
else if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
|
||||
{
|
||||
particle.scale.set(this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale));
|
||||
}
|
||||
else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y))
|
||||
{
|
||||
particle.scale.set(this.game.rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), this.game.rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y));
|
||||
}
|
||||
|
||||
if (Array.isArray(this._frames === 'object'))
|
||||
{
|
||||
particle.frame = this.game.rnd.pick(this._frames);
|
||||
}
|
||||
else
|
||||
{
|
||||
particle.frame = this._frames;
|
||||
}
|
||||
|
||||
if (this.autoAlpha)
|
||||
{
|
||||
particle.setAlphaData(this.alphaData);
|
||||
}
|
||||
else
|
||||
{
|
||||
particle.alpha = this.game.rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha);
|
||||
}
|
||||
|
||||
particle.blendMode = this.blendMode;
|
||||
|
||||
particle.body.updateBounds();
|
||||
|
||||
particle.body.bounce.setTo(this.bounce.x, this.bounce.y);
|
||||
|
||||
particle.body.velocity.x = this.game.rnd.integerInRange(this.minParticleSpeed.x, this.maxParticleSpeed.x);
|
||||
particle.body.velocity.y = this.game.rnd.integerInRange(this.minParticleSpeed.y, this.maxParticleSpeed.y);
|
||||
particle.body.angularVelocity = this.game.rnd.integerInRange(this.minRotation, this.maxRotation);
|
||||
|
||||
particle.body.gravity.y = this.gravity;
|
||||
|
||||
particle.body.drag.x = this.particleDrag.x;
|
||||
particle.body.drag.y = this.particleDrag.y;
|
||||
|
||||
particle.body.angularDrag = this.angularDrag;
|
||||
|
||||
particle.onEmit();
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the width and height of the emitter.
|
||||
* @method Phaser.Particles.Arcade.Emitter#setSize
|
||||
* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
|
||||
* @param {number} height - The desired height of the emitter.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
|
||||
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the X velocity range of the emitter.
|
||||
* @method Phaser.Particles.Arcade.Emitter#setXSpeed
|
||||
* @param {number} [min=0] - The minimum value for this range.
|
||||
* @param {number} [max=0] - The maximum value for this range.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
|
||||
|
||||
min = min || 0;
|
||||
max = max || 0;
|
||||
|
||||
this.minParticleSpeed.x = min;
|
||||
this.maxParticleSpeed.x = max;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the Y velocity range of the emitter.
|
||||
* @method Phaser.Particles.Arcade.Emitter#setYSpeed
|
||||
* @param {number} [min=0] - The minimum value for this range.
|
||||
* @param {number} [max=0] - The maximum value for this range.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
|
||||
|
||||
min = min || 0;
|
||||
max = max || 0;
|
||||
|
||||
this.minParticleSpeed.y = min;
|
||||
this.maxParticleSpeed.y = max;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the angular velocity constraints of the particles.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#setRotation
|
||||
* @param {number} [min=0] - The minimum value for this range.
|
||||
* @param {number} [max=0] - The maximum value for this range.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
|
||||
|
||||
min = min || 0;
|
||||
max = max || 0;
|
||||
|
||||
this.minRotation = min;
|
||||
this.maxRotation = max;
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the alpha constraints of the particles.
|
||||
* The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max.
|
||||
* If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#setAlpha
|
||||
* @param {number} [min=1] - The minimum value for this range.
|
||||
* @param {number} [max=1] - The maximum value for this range.
|
||||
* @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two.
|
||||
* @param {number} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
|
||||
* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) {
|
||||
|
||||
if (typeof min === 'undefined') { min = 1; }
|
||||
if (typeof max === 'undefined') { max = 1; }
|
||||
if (typeof rate === 'undefined') { rate = 0; }
|
||||
if (typeof ease === 'undefined') { ease = Phaser.Easing.Linear.None; }
|
||||
if (typeof yoyo === 'undefined') { yoyo = false; }
|
||||
|
||||
this.minParticleAlpha = min;
|
||||
this.maxParticleAlpha = max;
|
||||
this.autoAlpha = false;
|
||||
|
||||
if (rate > 0 && min !== max)
|
||||
{
|
||||
var tweenData = { v: min };
|
||||
var tween = this.game.make.tween(tweenData).to( { v: max }, rate, ease);
|
||||
tween.yoyo(yoyo);
|
||||
|
||||
this.alphaData = tween.generateData(60);
|
||||
|
||||
// Inverse it so we don't have to do array length look-ups in Particle update loops
|
||||
this.alphaData.reverse();
|
||||
this.autoAlpha = true;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* A more compact way of setting the scale constraints of the particles.
|
||||
* The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis.
|
||||
* If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit.
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#setScale
|
||||
* @param {number} [minX=1] - The minimum value of Particle.scale.x.
|
||||
* @param {number} [maxX=1] - The maximum value of Particle.scale.x.
|
||||
* @param {number} [minY=1] - The minimum value of Particle.scale.y.
|
||||
* @param {number} [maxY=1] - The maximum value of Particle.scale.y.
|
||||
* @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two.
|
||||
* @param {number} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
|
||||
* @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) {
|
||||
|
||||
if (typeof minX === 'undefined') { minX = 1; }
|
||||
if (typeof maxX === 'undefined') { maxX = 1; }
|
||||
if (typeof minY === 'undefined') { minY = 1; }
|
||||
if (typeof maxY === 'undefined') { maxY = 1; }
|
||||
if (typeof rate === 'undefined') { rate = 0; }
|
||||
if (typeof ease === 'undefined') { ease = Phaser.Easing.Linear.None; }
|
||||
if (typeof yoyo === 'undefined') { yoyo = false; }
|
||||
|
||||
// Reset these
|
||||
this.minParticleScale = 1;
|
||||
this.maxParticleScale = 1;
|
||||
|
||||
this._minParticleScale.set(minX, minY);
|
||||
this._maxParticleScale.set(maxX, maxY);
|
||||
|
||||
this.autoScale = false;
|
||||
|
||||
if (rate > 0 && (minX !== maxX) || (minY !== maxY))
|
||||
{
|
||||
var tweenData = { x: minX, y: minY };
|
||||
var tween = this.game.make.tween(tweenData).to( { x: maxX, y: maxY }, rate, ease);
|
||||
tween.yoyo(yoyo);
|
||||
|
||||
this.scaleData = tween.generateData(60);
|
||||
|
||||
// Inverse it so we don't have to do array length look-ups in Particle update loops
|
||||
this.scaleData.reverse();
|
||||
this.autoScale = true;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
|
||||
* If the object doesn't have a center property it will be set to object.x + object.width / 2
|
||||
*
|
||||
* @method Phaser.Particles.Arcade.Emitter#at
|
||||
* @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with.
|
||||
*/
|
||||
Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
|
||||
|
||||
if (object.center)
|
||||
{
|
||||
this.emitX = object.center.x;
|
||||
this.emitY = object.center.y;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.emitX = object.world.x + (object.anchor.x * object.width);
|
||||
this.emitY = object.world.y + (object.anchor.y * object.height);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#x
|
||||
* @property {number} x - Gets or sets the x position of the Emitter.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return this.emitX;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.emitX = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#y
|
||||
* @property {number} y - Gets or sets the y position of the Emitter.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return this.emitY;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.emitY = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#left
|
||||
* @property {number} left - Gets the left position of the Emitter.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
|
||||
|
||||
get: function () {
|
||||
return Math.floor(this.x - (this.width / 2));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#right
|
||||
* @property {number} right - Gets the right position of the Emitter.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return Math.floor(this.x + (this.width / 2));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#top
|
||||
* @property {number} top - Gets the top position of the Emitter.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
|
||||
|
||||
get: function () {
|
||||
return Math.floor(this.y - (this.height / 2));
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Particles.Arcade.Emitter#bottom
|
||||
* @property {number} bottom - Gets the bottom position of the Emitter.
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return Math.floor(this.y + (this.height / 2));
|
||||
}
|
||||
|
||||
});
|
||||
290
src/physics/Physics.js
Normal file
290
src/physics/Physics.js
Normal file
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Physics Manager is responsible for looking after all of the running physics systems.
|
||||
* Phaser supports 3 physics systems: Arcade Physics, P2 and Ninja Physics (with Box2D and Chipmunk in development)
|
||||
* Game Objects can belong to only 1 physics system, but you can have multiple systems active in a single game.
|
||||
*
|
||||
* For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
|
||||
* faster (due to being much simpler) Arcade Physics system.
|
||||
*
|
||||
* @class Phaser.Physics
|
||||
*
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game - A reference to the currently running game.
|
||||
* @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
|
||||
*/
|
||||
Phaser.Physics = function (game, config) {
|
||||
|
||||
config = config || {};
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {object} config - The physics configuration object as passed to the game on creation.
|
||||
*/
|
||||
this.config = config;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
|
||||
*/
|
||||
this.arcade = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
|
||||
*/
|
||||
this.p2 = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics System.
|
||||
*/
|
||||
this.ninja = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system (to be done).
|
||||
*/
|
||||
this.box2d = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
|
||||
*/
|
||||
this.chipmunk = null;
|
||||
|
||||
this.parseConfig();
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Physics.ARCADE = 0;
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Physics.P2JS = 1;
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Physics.NINJA = 2;
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Physics.BOX2D = 3;
|
||||
|
||||
/**
|
||||
* @const
|
||||
* @type {number}
|
||||
*/
|
||||
Phaser.Physics.CHIPMUNK = 5;
|
||||
|
||||
Phaser.Physics.prototype = {
|
||||
|
||||
/**
|
||||
* Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
|
||||
*
|
||||
* @method Phaser.Physics#parseConfig
|
||||
*/
|
||||
parseConfig: function () {
|
||||
|
||||
if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
|
||||
{
|
||||
// If Arcade isn't specified, we create it automatically if we can
|
||||
this.arcade = new Phaser.Physics.Arcade(this.game);
|
||||
this.game.time.deltaCap = 0.2;
|
||||
}
|
||||
|
||||
if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
|
||||
{
|
||||
this.ninja = new Phaser.Physics.Ninja(this.game);
|
||||
}
|
||||
|
||||
if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
|
||||
{
|
||||
this.p2 = new Phaser.Physics.P2(this.game, this.config);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This will create an instance of the requested physics simulation.
|
||||
* Phaser.Physics.Arcade is running by default, but all others need activating directly.
|
||||
* You can start the following physics systems:
|
||||
* Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
|
||||
* Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
|
||||
* Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
|
||||
*
|
||||
* @method Phaser.Physics#startSystem
|
||||
* @param {number} The physics system to start.
|
||||
*/
|
||||
startSystem: function (system) {
|
||||
|
||||
if (system === Phaser.Physics.ARCADE)
|
||||
{
|
||||
this.arcade = new Phaser.Physics.Arcade(this.game);
|
||||
}
|
||||
else if (system === Phaser.Physics.P2JS)
|
||||
{
|
||||
this.p2 = new Phaser.Physics.P2(this.game, this.config);
|
||||
}
|
||||
if (system === Phaser.Physics.NINJA)
|
||||
{
|
||||
this.ninja = new Phaser.Physics.Ninja(this.game);
|
||||
}
|
||||
else if (system === Phaser.Physics.BOX2D && this.box2d === null)
|
||||
{
|
||||
throw new Error('The Box2D physics system has not been implemented yet.');
|
||||
}
|
||||
else if (system === Phaser.Physics.CHIPMUNK && this.chipmunk === null)
|
||||
{
|
||||
throw new Error('The Chipmunk physics system has not been implemented yet.');
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This will create a default physics body on the given game object or array of objects.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
|
||||
* It can be for any of the physics systems that have been started:
|
||||
*
|
||||
* Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
|
||||
* Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
|
||||
* Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
|
||||
* Phaser.Physics.BOX2D and Phaser.Physics.CHIPMUNK are still in development.
|
||||
*
|
||||
* If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the
|
||||
* individual physics systems `enable` methods instead of using this generic one.
|
||||
*
|
||||
* @method Phaser.Physics#enable
|
||||
* @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
|
||||
* @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
|
||||
* @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
|
||||
*/
|
||||
enable: function (object, system, debug) {
|
||||
|
||||
if (typeof system === 'undefined') { system = Phaser.Physics.ARCADE; }
|
||||
if (typeof debug === 'undefined') { debug = false; }
|
||||
|
||||
if (system === Phaser.Physics.ARCADE)
|
||||
{
|
||||
this.arcade.enable(object);
|
||||
}
|
||||
else if (system === Phaser.Physics.P2JS && this.p2)
|
||||
{
|
||||
this.p2.enable(object, debug);
|
||||
}
|
||||
else if (system === Phaser.Physics.NINJA && this.ninja)
|
||||
{
|
||||
this.ninja.enableAABB(object);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* preUpdate checks.
|
||||
*
|
||||
* @method Phaser.Physics#preUpdate
|
||||
* @protected
|
||||
*/
|
||||
preUpdate: function () {
|
||||
|
||||
// ArcadePhysics / Ninja don't have a core to preUpdate
|
||||
|
||||
if (this.p2)
|
||||
{
|
||||
this.p2.preUpdate();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates all running physics systems.
|
||||
*
|
||||
* @method Phaser.Physics#update
|
||||
* @protected
|
||||
*/
|
||||
update: function () {
|
||||
|
||||
// ArcadePhysics / Ninja don't have a core to update
|
||||
|
||||
if (this.p2)
|
||||
{
|
||||
this.p2.update();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the physics bounds to match the world dimensions.
|
||||
*
|
||||
* @method Phaser.Physics#setBoundsToWorld
|
||||
* @protected
|
||||
*/
|
||||
setBoundsToWorld: function () {
|
||||
|
||||
if (this.arcade)
|
||||
{
|
||||
this.arcade.setBoundsToWorld();
|
||||
}
|
||||
|
||||
if (this.ninja)
|
||||
{
|
||||
this.ninja.setBoundsToWorld();
|
||||
}
|
||||
|
||||
if (this.p2)
|
||||
{
|
||||
this.p2.setBoundsToWorld();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
|
||||
*
|
||||
* @method Phaser.Physics#clear
|
||||
* @protected
|
||||
*/
|
||||
clear: function () {
|
||||
|
||||
if (this.p2)
|
||||
{
|
||||
this.p2.clear();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
|
||||
*
|
||||
* @method Phaser.Physics#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
if (this.p2)
|
||||
{
|
||||
this.p2.destroy();
|
||||
}
|
||||
|
||||
this.arcade = null;
|
||||
this.ninja = null;
|
||||
this.p2 = null;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.prototype.constructor = Phaser.Physics;
|
||||
809
src/physics/arcade/Body.js
Normal file
809
src/physics/arcade/Body.js
Normal file
@@ -0,0 +1,809 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
|
||||
* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
|
||||
*
|
||||
* @class Phaser.Physics.Arcade.Body
|
||||
* @classdesc Arcade Physics Body Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
|
||||
*/
|
||||
Phaser.Physics.Arcade.Body = function (sprite) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
|
||||
*/
|
||||
this.sprite = sprite;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = sprite.game;
|
||||
|
||||
/**
|
||||
* @property {number} type - The type of physics system this body belongs to.
|
||||
*/
|
||||
this.type = Phaser.Physics.ARCADE;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
|
||||
*/
|
||||
this.offset = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} position - The position of the physics body.
|
||||
* @readonly
|
||||
*/
|
||||
this.position = new Phaser.Point(sprite.x, sprite.y);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} prev - The previous position of the physics body.
|
||||
* @readonly
|
||||
*/
|
||||
this.prev = new Phaser.Point(this.position.x, this.position.y);
|
||||
|
||||
/**
|
||||
* @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
|
||||
* @default
|
||||
*/
|
||||
this.allowRotation = true;
|
||||
|
||||
/**
|
||||
* @property {number} rotation - The amount the Body is rotated.
|
||||
*/
|
||||
this.rotation = sprite.rotation;
|
||||
|
||||
/**
|
||||
* @property {number} preRotation - The previous rotation of the physics body.
|
||||
* @readonly
|
||||
*/
|
||||
this.preRotation = sprite.rotation;
|
||||
|
||||
/**
|
||||
* @property {number} sourceWidth - The un-scaled original size.
|
||||
* @readonly
|
||||
*/
|
||||
this.sourceWidth = sprite.texture.frame.width;
|
||||
|
||||
/**
|
||||
* @property {number} sourceHeight - The un-scaled original size.
|
||||
* @readonly
|
||||
*/
|
||||
this.sourceHeight = sprite.texture.frame.height;
|
||||
|
||||
/**
|
||||
* @property {number} width - The calculated width of the physics body.
|
||||
*/
|
||||
this.width = sprite.width;
|
||||
|
||||
/**
|
||||
* @property .numInternal ID cache
|
||||
*/
|
||||
this.height = sprite.height;
|
||||
|
||||
/**
|
||||
* @property {number} halfWidth - The calculated width / 2 of the physics body.
|
||||
*/
|
||||
this.halfWidth = Math.abs(sprite.width / 2);
|
||||
|
||||
/**
|
||||
* @property {number} halfHeight - The calculated height / 2 of the physics body.
|
||||
*/
|
||||
this.halfHeight = Math.abs(sprite.height / 2);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} center - The center coordinate of the Physics Body.
|
||||
*/
|
||||
this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
|
||||
*/
|
||||
this.velocity = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} newVelocity - New velocity.
|
||||
* @readonly
|
||||
*/
|
||||
this.newVelocity = new Phaser.Point(0, 0);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax.
|
||||
*/
|
||||
this.deltaMax = new Phaser.Point(0, 0);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body.
|
||||
*/
|
||||
this.acceleration = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} drag - The drag applied to the motion of the Body.
|
||||
*/
|
||||
this.drag = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local.
|
||||
* @default
|
||||
*/
|
||||
this.allowGravity = true;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} gravity - A local gravity applied to this Body. If non-zero this over rides any world gravity, unless Body.allowGravity is set to false.
|
||||
*/
|
||||
this.gravity = new Phaser.Point(0, 0);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
|
||||
*/
|
||||
this.bounce = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
|
||||
* @default
|
||||
*/
|
||||
this.maxVelocity = new Phaser.Point(10000, 10000);
|
||||
|
||||
/**
|
||||
* @property {number} angularVelocity - The angular velocity in pixels per second sq. of the Body.
|
||||
* @default
|
||||
*/
|
||||
this.angularVelocity = 0;
|
||||
|
||||
/**
|
||||
* @property {number} angularAcceleration - The angular acceleration in pixels per second sq. of the Body.
|
||||
* @default
|
||||
*/
|
||||
this.angularAcceleration = 0;
|
||||
|
||||
/**
|
||||
* @property {number} angularDrag - The angular drag applied to the rotation of the Body.
|
||||
* @default
|
||||
*/
|
||||
this.angularDrag = 0;
|
||||
|
||||
/**
|
||||
* @property {number} maxAngular - The maximum angular velocity in pixels per second sq. that the Body can reach.
|
||||
* @default
|
||||
*/
|
||||
this.maxAngular = 1000;
|
||||
|
||||
/**
|
||||
* @property {number} mass - The mass of the Body.
|
||||
* @default
|
||||
*/
|
||||
this.mass = 1;
|
||||
|
||||
/**
|
||||
* @property {number} angle - The angle of the Body in radians as calculated by its velocity, rather than its visual angle.
|
||||
* @readonly
|
||||
*/
|
||||
this.angle = 0;
|
||||
|
||||
/**
|
||||
* @property {number} speed - The speed of the Body as calculated by its velocity.
|
||||
* @readonly
|
||||
*/
|
||||
this.speed = 0;
|
||||
|
||||
/**
|
||||
* @property {number} facing - A const reference to the direction the Body is traveling or facing.
|
||||
* @default
|
||||
*/
|
||||
this.facing = Phaser.NONE;
|
||||
|
||||
/**
|
||||
* @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
|
||||
* @default
|
||||
*/
|
||||
this.immovable = false;
|
||||
|
||||
/**
|
||||
* If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never
|
||||
* actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen.
|
||||
* If you want the physics system to move the body around, then set moves to true.
|
||||
* @property {boolean} moves - Set to true to allow the Physics system to move this Body, other false to move it manually.
|
||||
* @default
|
||||
*/
|
||||
this.moves = true;
|
||||
|
||||
/**
|
||||
* This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
|
||||
* Used in combination with your own collision processHandler you can create whatever type of collision response you need.
|
||||
* @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
|
||||
* @default
|
||||
*/
|
||||
this.customSeparateX = false;
|
||||
|
||||
/**
|
||||
* This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
|
||||
* Used in combination with your own collision processHandler you can create whatever type of collision response you need.
|
||||
* @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
|
||||
* @default
|
||||
*/
|
||||
this.customSeparateY = false;
|
||||
|
||||
/**
|
||||
* When this body collides with another, the amount of overlap is stored here.
|
||||
* @property {number} overlapX - The amount of horizontal overlap during the collision.
|
||||
*/
|
||||
this.overlapX = 0;
|
||||
|
||||
/**
|
||||
* When this body collides with another, the amount of overlap is stored here.
|
||||
* @property {number} overlapY - The amount of vertical overlap during the collision.
|
||||
*/
|
||||
this.overlapY = 0;
|
||||
|
||||
/**
|
||||
* If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true.
|
||||
* @property {boolean} embedded - Body embed value.
|
||||
*/
|
||||
this.embedded = false;
|
||||
|
||||
/**
|
||||
* A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
|
||||
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
|
||||
*/
|
||||
this.collideWorldBounds = false;
|
||||
|
||||
/**
|
||||
* Set the checkCollision properties to control which directions collision is processed for this Body.
|
||||
* For example checkCollision.up = false means it won't collide when the collision happened while moving up.
|
||||
* @property {object} checkCollision - An object containing allowed collision.
|
||||
*/
|
||||
this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
|
||||
|
||||
/**
|
||||
* This object is populated with boolean values when the Body collides with another.
|
||||
* touching.up = true means the collision happened to the top of this Body for example.
|
||||
* @property {object} touching - An object containing touching results.
|
||||
*/
|
||||
this.touching = { none: true, up: false, down: false, left: false, right: false };
|
||||
|
||||
/**
|
||||
* This object is populated with previous touching values from the bodies previous collision.
|
||||
* @property {object} wasTouching - An object containing previous touching results.
|
||||
*/
|
||||
this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
|
||||
|
||||
/**
|
||||
* This object is populated with boolean values when the Body collides with the World bounds or a Tile.
|
||||
* For example if blocked.up is true then the Body cannot move up.
|
||||
* @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
|
||||
*/
|
||||
this.blocked = { up: false, down: false, left: false, right: false };
|
||||
|
||||
/**
|
||||
* If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step.
|
||||
* Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height.
|
||||
* @property {Phaser.Point} tilePadding - Extra padding to be added to this sprites dimensions when checking for tile collision.
|
||||
*/
|
||||
this.tilePadding = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {number} phaser - Is this Body in a preUpdate (1) or postUpdate (2) state?
|
||||
*/
|
||||
this.phase = 0;
|
||||
|
||||
/**
|
||||
* @property {boolean} _reset - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._reset = true;
|
||||
|
||||
/**
|
||||
* @property {number} _sx - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._sx = sprite.scale.x;
|
||||
|
||||
/**
|
||||
* @property {number} _sy - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._sy = sprite.scale.y;
|
||||
|
||||
/**
|
||||
* @property {number} _dx - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._dx = 0;
|
||||
|
||||
/**
|
||||
* @property {number} _dy - Internal cache var.
|
||||
* @private
|
||||
*/
|
||||
this._dy = 0;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.Arcade.Body.prototype = {
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#updateBounds
|
||||
* @protected
|
||||
*/
|
||||
updateBounds: function () {
|
||||
|
||||
var asx = Math.abs(this.sprite.scale.x);
|
||||
var asy = Math.abs(this.sprite.scale.y);
|
||||
|
||||
if (asx !== this._sx || asy !== this._sy)
|
||||
{
|
||||
this.width = this.sourceWidth * asx;
|
||||
this.height = this.sourceHeight * asy;
|
||||
this.halfWidth = Math.floor(this.width / 2);
|
||||
this.halfHeight = Math.floor(this.height / 2);
|
||||
this._sx = asx;
|
||||
this._sy = asy;
|
||||
this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
|
||||
|
||||
this._reset = true;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#preUpdate
|
||||
* @protected
|
||||
*/
|
||||
preUpdate: function () {
|
||||
|
||||
this.phase = 1;
|
||||
|
||||
// Store and reset collision flags
|
||||
this.wasTouching.none = this.touching.none;
|
||||
this.wasTouching.up = this.touching.up;
|
||||
this.wasTouching.down = this.touching.down;
|
||||
this.wasTouching.left = this.touching.left;
|
||||
this.wasTouching.right = this.touching.right;
|
||||
|
||||
this.touching.none = true;
|
||||
this.touching.up = false;
|
||||
this.touching.down = false;
|
||||
this.touching.left = false;
|
||||
this.touching.right = false;
|
||||
|
||||
this.blocked.up = false;
|
||||
this.blocked.down = false;
|
||||
this.blocked.left = false;
|
||||
this.blocked.right = false;
|
||||
|
||||
this.embedded = false;
|
||||
|
||||
this.updateBounds();
|
||||
|
||||
this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x;
|
||||
this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y;
|
||||
this.rotation = this.sprite.angle;
|
||||
|
||||
this.preRotation = this.rotation;
|
||||
|
||||
if (this._reset || this.sprite._cache[4] === 1)
|
||||
{
|
||||
this.prev.x = this.position.x;
|
||||
this.prev.y = this.position.y;
|
||||
}
|
||||
|
||||
if (this.moves)
|
||||
{
|
||||
this.game.physics.arcade.updateMotion(this);
|
||||
|
||||
this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
|
||||
|
||||
this.position.x += this.newVelocity.x;
|
||||
this.position.y += this.newVelocity.y;
|
||||
|
||||
if (this.position.x !== this.prev.x || this.position.y !== this.prev.y)
|
||||
{
|
||||
this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
|
||||
this.angle = Math.atan2(this.velocity.y, this.velocity.x);
|
||||
}
|
||||
|
||||
// Now the State update will throw collision checks at the Body
|
||||
// And finally we'll integrate the new position back to the Sprite in postUpdate
|
||||
|
||||
if (this.collideWorldBounds)
|
||||
{
|
||||
this.checkWorldBounds();
|
||||
}
|
||||
}
|
||||
|
||||
this._dx = this.deltaX();
|
||||
this._dy = this.deltaY();
|
||||
|
||||
this._reset = false;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#postUpdate
|
||||
* @protected
|
||||
*/
|
||||
postUpdate: function () {
|
||||
|
||||
// Only allow postUpdate to be called once per frame
|
||||
if (this.phase === 2)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.phase = 2;
|
||||
|
||||
if (this.deltaX() < 0)
|
||||
{
|
||||
this.facing = Phaser.LEFT;
|
||||
}
|
||||
else if (this.deltaX() > 0)
|
||||
{
|
||||
this.facing = Phaser.RIGHT;
|
||||
}
|
||||
|
||||
if (this.deltaY() < 0)
|
||||
{
|
||||
this.facing = Phaser.UP;
|
||||
}
|
||||
else if (this.deltaY() > 0)
|
||||
{
|
||||
this.facing = Phaser.DOWN;
|
||||
}
|
||||
|
||||
if (this.moves)
|
||||
{
|
||||
this._dx = this.deltaX();
|
||||
this._dy = this.deltaY();
|
||||
|
||||
if (this.deltaMax.x !== 0 && this._dx !== 0)
|
||||
{
|
||||
if (this._dx < 0 && this._dx < -this.deltaMax.x)
|
||||
{
|
||||
this._dx = -this.deltaMax.x;
|
||||
}
|
||||
else if (this._dx > 0 && this._dx > this.deltaMax.x)
|
||||
{
|
||||
this._dx = this.deltaMax.x;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.deltaMax.y !== 0 && this._dy !== 0)
|
||||
{
|
||||
if (this._dy < 0 && this._dy < -this.deltaMax.y)
|
||||
{
|
||||
this._dy = -this.deltaMax.y;
|
||||
}
|
||||
else if (this._dy > 0 && this._dy > this.deltaMax.y)
|
||||
{
|
||||
this._dy = this.deltaMax.y;
|
||||
}
|
||||
}
|
||||
|
||||
this.sprite.x += this._dx;
|
||||
this.sprite.y += this._dy;
|
||||
}
|
||||
|
||||
this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
|
||||
|
||||
if (this.allowRotation)
|
||||
{
|
||||
this.sprite.angle += this.deltaZ();
|
||||
}
|
||||
|
||||
this.prev.x = this.position.x;
|
||||
this.prev.y = this.position.y;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes this bodies reference to its parent sprite, freeing it up for gc.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.sprite = null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#checkWorldBounds
|
||||
* @protected
|
||||
*/
|
||||
checkWorldBounds: function () {
|
||||
|
||||
if (this.position.x < this.game.physics.arcade.bounds.x && this.game.physics.arcade.checkCollision.left)
|
||||
{
|
||||
this.position.x = this.game.physics.arcade.bounds.x;
|
||||
this.velocity.x *= -this.bounce.x;
|
||||
this.blocked.left = true;
|
||||
}
|
||||
else if (this.right > this.game.physics.arcade.bounds.right && this.game.physics.arcade.checkCollision.right)
|
||||
{
|
||||
this.position.x = this.game.physics.arcade.bounds.right - this.width;
|
||||
this.velocity.x *= -this.bounce.x;
|
||||
this.blocked.right = true;
|
||||
}
|
||||
|
||||
if (this.position.y < this.game.physics.arcade.bounds.y && this.game.physics.arcade.checkCollision.up)
|
||||
{
|
||||
this.position.y = this.game.physics.arcade.bounds.y;
|
||||
this.velocity.y *= -this.bounce.y;
|
||||
this.blocked.up = true;
|
||||
}
|
||||
else if (this.bottom > this.game.physics.arcade.bounds.bottom && this.game.physics.arcade.checkCollision.down)
|
||||
{
|
||||
this.position.y = this.game.physics.arcade.bounds.bottom - this.height;
|
||||
this.velocity.y *= -this.bounce.y;
|
||||
this.blocked.down = true;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* You can modify the size of the physics Body to be any dimension you need.
|
||||
* So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which
|
||||
* is the position of the Body relative to the top-left of the Sprite.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#setSize
|
||||
* @param {number} width - The width of the Body.
|
||||
* @param {number} height - The height of the Body.
|
||||
* @param {number} offsetX - The X offset of the Body from the Sprite position.
|
||||
* @param {number} offsetY - The Y offset of the Body from the Sprite position.
|
||||
*/
|
||||
setSize: function (width, height, offsetX, offsetY) {
|
||||
|
||||
offsetX = offsetX || this.offset.x;
|
||||
offsetY = offsetY || this.offset.y;
|
||||
|
||||
this.sourceWidth = width;
|
||||
this.sourceHeight = height;
|
||||
this.width = this.sourceWidth * this._sx;
|
||||
this.height = this.sourceHeight * this._sy;
|
||||
this.halfWidth = Math.floor(this.width / 2);
|
||||
this.halfHeight = Math.floor(this.height / 2);
|
||||
this.offset.setTo(offsetX, offsetY);
|
||||
|
||||
this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets all Body values (velocity, acceleration, rotation, etc)
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#reset
|
||||
* @param {number} x - The new x position of the Body.
|
||||
* @param {number} y - The new y position of the Body.
|
||||
*/
|
||||
reset: function (x, y) {
|
||||
|
||||
this.velocity.set(0);
|
||||
this.acceleration.set(0);
|
||||
|
||||
this.angularVelocity = 0;
|
||||
this.angularAcceleration = 0;
|
||||
|
||||
this.position.x = (x - (this.sprite.anchor.x * this.width)) + this.offset.x;
|
||||
this.position.y = (y - (this.sprite.anchor.y * this.height)) + this.offset.y;
|
||||
|
||||
this.prev.x = this.position.x;
|
||||
this.prev.y = this.position.y;
|
||||
|
||||
this.rotation = this.sprite.angle;
|
||||
this.preRotation = this.rotation;
|
||||
|
||||
this._sx = this.sprite.scale.x;
|
||||
this._sy = this.sprite.scale.y;
|
||||
|
||||
this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Tests if a world point lies within this Body.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#hitTest
|
||||
* @param {number} x - The world x coordinate to test.
|
||||
* @param {number} y - The world y coordinate to test.
|
||||
* @return {boolean} True if the given coordinates are inside this Body, otherwise false.
|
||||
*/
|
||||
hitTest: function (x, y) {
|
||||
|
||||
return Phaser.Rectangle.contains(this, x, y);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if the bottom of this Body is in contact with either the world bounds or a tile.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#onFloor
|
||||
* @return {boolean} True if in contact with either the world bounds or a tile.
|
||||
*/
|
||||
onFloor: function () {
|
||||
return this.blocked.down;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns true if either side of this Body is in contact with either the world bounds or a tile.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#onWall
|
||||
* @return {boolean} True if in contact with either the world bounds or a tile.
|
||||
*/
|
||||
onWall: function () {
|
||||
return (this.blocked.left || this.blocked.right);
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the absolute delta x value.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#deltaAbsX
|
||||
* @return {number} The absolute delta value.
|
||||
*/
|
||||
deltaAbsX: function () {
|
||||
return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the absolute delta y value.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#deltaAbsY
|
||||
* @return {number} The absolute delta value.
|
||||
*/
|
||||
deltaAbsY: function () {
|
||||
return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the delta x value. The difference between Body.x now and in the previous step.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#deltaX
|
||||
* @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
|
||||
*/
|
||||
deltaX: function () {
|
||||
return this.position.x - this.prev.x;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the delta y value. The difference between Body.y now and in the previous step.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#deltaY
|
||||
* @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
|
||||
*/
|
||||
deltaY: function () {
|
||||
return this.position.y - this.prev.y;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the delta z value. The difference between Body.rotation now and in the previous step.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#deltaZ
|
||||
* @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
|
||||
*/
|
||||
deltaZ: function () {
|
||||
return this.rotation - this.preRotation;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Arcade.Body#bottom
|
||||
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.position.y + this.height;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Arcade.Body#right
|
||||
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.position.x + this.width;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Arcade.Body#x
|
||||
* @property {number} x - The x position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return this.position.x;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.position.x = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Arcade.Body#y
|
||||
* @property {number} y - The y position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return this.position.y;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.position.y = value;
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* Render Sprite Body.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#renderDebug
|
||||
* @param {object} context - The context to render to.
|
||||
* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
|
||||
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
|
||||
* @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
|
||||
*/
|
||||
Phaser.Physics.Arcade.Body.render = function (context, body, filled, color) {
|
||||
|
||||
if (typeof filled === 'undefined') { filled = true; }
|
||||
|
||||
color = color || 'rgba(0,255,0,0.4)';
|
||||
|
||||
if (filled)
|
||||
{
|
||||
context.fillStyle = color;
|
||||
context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
context.strokeStyle = color;
|
||||
context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Render Sprite Body Physics Data as text.
|
||||
*
|
||||
* @method Phaser.Physics.Arcade.Body#renderBodyInfo
|
||||
* @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
|
||||
* @param {number} x - X position of the debug info to be rendered.
|
||||
* @param {number} y - Y position of the debug info to be rendered.
|
||||
* @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
|
||||
*/
|
||||
Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) {
|
||||
|
||||
debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height);
|
||||
debug.line('velocity x: ' + body.velocity.x.toFixed(2), 'y: ' + body.velocity.y.toFixed(2), 'deltaX: ' + body._dx.toFixed(2), 'deltaY: ' + body._dy.toFixed(2));
|
||||
debug.line('acceleration x: ' + body.acceleration.x.toFixed(2), 'y: ' + body.acceleration.y.toFixed(2), 'speed: ' + body.speed.toFixed(2), 'angle: ' + body.angle.toFixed(2));
|
||||
debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2));
|
||||
debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down);
|
||||
debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
|
||||
1732
src/physics/arcade/World.js
Normal file
1732
src/physics/arcade/World.js
Normal file
File diff suppressed because it is too large
Load Diff
1008
src/physics/ninja/AABB.js
Normal file
1008
src/physics/ninja/AABB.js
Normal file
File diff suppressed because it is too large
Load Diff
548
src/physics/ninja/Body.js
Normal file
548
src/physics/ninja/Body.js
Normal file
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
|
||||
* the Sprite itself. For example you can set the velocity, bounce values etc all on the Body.
|
||||
*
|
||||
* @class Phaser.Physics.Ninja.Body
|
||||
* @classdesc Ninja Physics Body Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.Ninja} system - The physics system this Body belongs to.
|
||||
* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
|
||||
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
|
||||
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
|
||||
* @param {number} [radius=16] - If this body is using a Circle shape this controls the radius.
|
||||
* @param {number} [x=0] - The x coordinate of this Body. This is only used if a sprite is not provided.
|
||||
* @param {number} [y=0] - The y coordinate of this Body. This is only used if a sprite is not provided.
|
||||
* @param {number} [width=0] - The width of this Body. This is only used if a sprite is not provided.
|
||||
* @param {number} [height=0] - The height of this Body. This is only used if a sprite is not provided.
|
||||
*/
|
||||
Phaser.Physics.Ninja.Body = function (system, sprite, type, id, radius, x, y, width, height) {
|
||||
|
||||
sprite = sprite || null;
|
||||
|
||||
if (typeof type === 'undefined') { type = 1; }
|
||||
if (typeof id === 'undefined') { id = 1; }
|
||||
if (typeof radius === 'undefined') { radius = 16; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
|
||||
*/
|
||||
this.sprite = sprite;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = system.game;
|
||||
|
||||
/**
|
||||
* @property {number} type - The type of physics system this body belongs to.
|
||||
*/
|
||||
this.type = Phaser.Physics.NINJA;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja} system - The parent physics system.
|
||||
*/
|
||||
this.system = system;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja.AABB} aabb - The AABB object this body is using for collision.
|
||||
*/
|
||||
this.aabb = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja.Tile} tile - The Tile object this body is using for collision.
|
||||
*/
|
||||
this.tile = null;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja.Circle} circle - The Circle object this body is using for collision.
|
||||
*/
|
||||
this.circle = null;
|
||||
|
||||
/**
|
||||
* @property {object} shape - A local reference to the body shape.
|
||||
*/
|
||||
this.shape = null;
|
||||
|
||||
// Setting drag to 0 and friction to 0 means you get a normalised speed (px psec)
|
||||
|
||||
/**
|
||||
* @property {number} drag - The drag applied to this object as it moves.
|
||||
* @default
|
||||
*/
|
||||
this.drag = 1;
|
||||
|
||||
/**
|
||||
* @property {number} friction - The friction applied to this object as it moves.
|
||||
* @default
|
||||
*/
|
||||
this.friction = 0.05;
|
||||
|
||||
/**
|
||||
* @property {number} gravityScale - How much of the world gravity should be applied to this object? 1 = all of it, 0.5 = 50%, etc.
|
||||
* @default
|
||||
*/
|
||||
this.gravityScale = 1;
|
||||
|
||||
/**
|
||||
* @property {number} bounce - The bounciness of this object when it collides. A value between 0 and 1. We recommend setting it to 0.999 to avoid jittering.
|
||||
* @default
|
||||
*/
|
||||
this.bounce = 0.3;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body.
|
||||
*/
|
||||
this.velocity = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {number} facing - A const reference to the direction the Body is traveling or facing.
|
||||
* @default
|
||||
*/
|
||||
this.facing = Phaser.NONE;
|
||||
|
||||
/**
|
||||
* @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. Not fully implemented.
|
||||
* @default
|
||||
*/
|
||||
this.immovable = false;
|
||||
|
||||
/**
|
||||
* A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
|
||||
* @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
|
||||
*/
|
||||
this.collideWorldBounds = true;
|
||||
|
||||
/**
|
||||
* Set the checkCollision properties to control which directions collision is processed for this Body.
|
||||
* For example checkCollision.up = false means it won't collide when the collision happened while moving up.
|
||||
* @property {object} checkCollision - An object containing allowed collision.
|
||||
*/
|
||||
this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
|
||||
|
||||
/**
|
||||
* This object is populated with boolean values when the Body collides with another.
|
||||
* touching.up = true means the collision happened to the top of this Body for example.
|
||||
* @property {object} touching - An object containing touching results.
|
||||
*/
|
||||
this.touching = { none: true, up: false, down: false, left: false, right: false };
|
||||
|
||||
/**
|
||||
* This object is populated with previous touching values from the bodies previous collision.
|
||||
* @property {object} wasTouching - An object containing previous touching results.
|
||||
*/
|
||||
this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
|
||||
|
||||
/**
|
||||
* @property {number} maxSpeed - The maximum speed this body can travel at (taking drag and friction into account)
|
||||
* @default
|
||||
*/
|
||||
this.maxSpeed = 8;
|
||||
|
||||
if (sprite)
|
||||
{
|
||||
x = sprite.x;
|
||||
y = sprite.y;
|
||||
width = sprite.width;
|
||||
height = sprite.height;
|
||||
|
||||
if (sprite.anchor.x === 0)
|
||||
{
|
||||
x += (sprite.width * 0.5);
|
||||
}
|
||||
|
||||
if (sprite.anchor.y === 0)
|
||||
{
|
||||
y += (sprite.height * 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 1)
|
||||
{
|
||||
this.aabb = new Phaser.Physics.Ninja.AABB(this, x, y, width, height);
|
||||
this.shape = this.aabb;
|
||||
}
|
||||
else if (type === 2)
|
||||
{
|
||||
this.circle = new Phaser.Physics.Ninja.Circle(this, x, y, radius);
|
||||
this.shape = this.circle;
|
||||
}
|
||||
else if (type === 3)
|
||||
{
|
||||
this.tile = new Phaser.Physics.Ninja.Tile(this, x, y, width, height, id);
|
||||
this.shape = this.tile;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.Ninja.Body.prototype = {
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#preUpdate
|
||||
* @protected
|
||||
*/
|
||||
preUpdate: function () {
|
||||
|
||||
// Store and reset collision flags
|
||||
this.wasTouching.none = this.touching.none;
|
||||
this.wasTouching.up = this.touching.up;
|
||||
this.wasTouching.down = this.touching.down;
|
||||
this.wasTouching.left = this.touching.left;
|
||||
this.wasTouching.right = this.touching.right;
|
||||
|
||||
this.touching.none = true;
|
||||
this.touching.up = false;
|
||||
this.touching.down = false;
|
||||
this.touching.left = false;
|
||||
this.touching.right = false;
|
||||
|
||||
this.shape.integrate();
|
||||
|
||||
if (this.collideWorldBounds)
|
||||
{
|
||||
this.shape.collideWorldBounds();
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal method.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#postUpdate
|
||||
* @protected
|
||||
*/
|
||||
postUpdate: function () {
|
||||
|
||||
if (this.sprite)
|
||||
{
|
||||
if (this.sprite.type === Phaser.TILESPRITE)
|
||||
{
|
||||
// TileSprites don't use their anchor property, so we need to adjust the coordinates
|
||||
this.sprite.x = this.shape.pos.x - this.shape.xw;
|
||||
this.sprite.y = this.shape.pos.y - this.shape.yw;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.sprite.x = this.shape.pos.x;
|
||||
this.sprite.y = this.shape.pos.y;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.velocity.x < 0)
|
||||
{
|
||||
this.facing = Phaser.LEFT;
|
||||
}
|
||||
else if (this.velocity.x > 0)
|
||||
{
|
||||
this.facing = Phaser.RIGHT;
|
||||
}
|
||||
|
||||
if (this.velocity.y < 0)
|
||||
{
|
||||
this.facing = Phaser.UP;
|
||||
}
|
||||
else if (this.velocity.y > 0)
|
||||
{
|
||||
this.facing = Phaser.DOWN;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Stops all movement of this body.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#setZeroVelocity
|
||||
*/
|
||||
setZeroVelocity: function () {
|
||||
|
||||
this.shape.oldpos.x = this.shape.pos.x;
|
||||
this.shape.oldpos.y = this.shape.pos.y;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Moves the Body forwards based on its current angle and the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveTo
|
||||
* @param {number} speed - The speed at which it should move forwards.
|
||||
* @param {number} angle - The angle in which it should move, given in degrees.
|
||||
*/
|
||||
moveTo: function (speed, angle) {
|
||||
|
||||
var magnitude = speed * this.game.time.physicsElapsed;
|
||||
var angle = this.game.math.degToRad(angle);
|
||||
|
||||
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
|
||||
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Moves the Body backwards based on its current angle and the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveBackward
|
||||
* @param {number} speed - The speed at which it should move backwards.
|
||||
* @param {number} angle - The angle in which it should move, given in degrees.
|
||||
*/
|
||||
moveFrom: function (speed, angle) {
|
||||
|
||||
var magnitude = -speed * this.game.time.physicsElapsed;
|
||||
var angle = this.game.math.degToRad(angle);
|
||||
|
||||
this.shape.pos.x = this.shape.oldpos.x + (magnitude * Math.cos(angle));
|
||||
this.shape.pos.y = this.shape.oldpos.y + (magnitude * Math.sin(angle));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveLeft
|
||||
* @param {number} speed - The speed at which it should move to the left, in pixels per second.
|
||||
*/
|
||||
moveLeft: function (speed) {
|
||||
|
||||
var fx = -speed * this.game.time.physicsElapsed;
|
||||
|
||||
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveRight
|
||||
* @param {number} speed - The speed at which it should move to the right, in pixels per second.
|
||||
*/
|
||||
moveRight: function (speed) {
|
||||
|
||||
var fx = speed * this.game.time.physicsElapsed;
|
||||
|
||||
this.shape.pos.x = this.shape.oldpos.x + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.x - this.shape.oldpos.x + fx));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveUp
|
||||
* @param {number} speed - The speed at which it should move up, in pixels per second.
|
||||
*/
|
||||
moveUp: function (speed) {
|
||||
|
||||
var fx = -speed * this.game.time.physicsElapsed;
|
||||
|
||||
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
|
||||
* The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
|
||||
*
|
||||
* @method Phaser.Physics.Body#moveDown
|
||||
* @param {number} speed - The speed at which it should move down, in pixels per second.
|
||||
*/
|
||||
moveDown: function (speed) {
|
||||
|
||||
var fx = speed * this.game.time.physicsElapsed;
|
||||
|
||||
this.shape.pos.y = this.shape.oldpos.y + Math.min(this.maxSpeed, Math.max(-this.maxSpeed, this.shape.pos.y - this.shape.oldpos.y + fx));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Resets all Body values and repositions on the Sprite.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#reset
|
||||
*/
|
||||
reset: function () {
|
||||
|
||||
this.velocity.set(0);
|
||||
|
||||
this.shape.pos.x = this.sprite.x;
|
||||
this.shape.pos.y = this.sprite.y;
|
||||
|
||||
this.shape.oldpos.copyFrom(this.shape.pos);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the absolute delta x value.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#deltaAbsX
|
||||
* @return {number} The absolute delta value.
|
||||
*/
|
||||
deltaAbsX: function () {
|
||||
return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the absolute delta y value.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#deltaAbsY
|
||||
* @return {number} The absolute delta value.
|
||||
*/
|
||||
deltaAbsY: function () {
|
||||
return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the delta x value. The difference between Body.x now and in the previous step.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#deltaX
|
||||
* @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
|
||||
*/
|
||||
deltaX: function () {
|
||||
return this.shape.pos.x - this.shape.oldpos.x;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the delta y value. The difference between Body.y now and in the previous step.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#deltaY
|
||||
* @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
|
||||
*/
|
||||
deltaY: function () {
|
||||
return this.shape.pos.y - this.shape.oldpos.y;
|
||||
},
|
||||
|
||||
/**
|
||||
* Destroys this body's reference to the sprite and system, and destroys its shape.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Body#destroy
|
||||
*/
|
||||
destroy: function() {
|
||||
this.sprite = null;
|
||||
this.system = null;
|
||||
this.aabb = null;
|
||||
this.tile = null;
|
||||
this.circle = null;
|
||||
|
||||
this.shape.destroy();
|
||||
this.shape = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#x
|
||||
* @property {number} x - The x position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.pos.x;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.shape.pos.x = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#y
|
||||
* @property {number} y - The y position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.pos.y;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.shape.pos.y = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#width
|
||||
* @property {number} width - The width of this Body
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "width", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.width;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#height
|
||||
* @property {number} height - The height of this Body
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "height", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.height;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#bottom
|
||||
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.pos.y + this.shape.yw;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#right
|
||||
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.shape.pos.x + this.shape.xw;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#speed
|
||||
* @property {number} speed - The speed of this Body
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "speed", {
|
||||
|
||||
get: function () {
|
||||
return Math.sqrt(this.shape.velocity.x * this.shape.velocity.x + this.shape.velocity.y * this.shape.velocity.y);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Body#angle
|
||||
* @property {number} angle - The angle of this Body
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Body.prototype, "angle", {
|
||||
|
||||
get: function () {
|
||||
return Math.atan2(this.shape.velocity.y, this.shape.velocity.x);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
2624
src/physics/ninja/Circle.js
Normal file
2624
src/physics/ninja/Circle.js
Normal file
File diff suppressed because it is too large
Load Diff
772
src/physics/ninja/Tile.js
Normal file
772
src/physics/ninja/Tile.js
Normal file
@@ -0,0 +1,772 @@
|
||||
/* jshint camelcase: false */
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Ninja Physics Tile constructor.
|
||||
* A Tile is defined by its width, height and type. It's type can include slope data, such as 45 degree slopes, or convex slopes.
|
||||
* Understand that for any type including a slope (types 2 to 29) the Tile must be SQUARE, i.e. have an equal width and height.
|
||||
* Also note that as Tiles are primarily used for levels they have gravity disabled and world bounds collision disabled by default.
|
||||
*
|
||||
* Note: This class could be massively optimised and reduced in size. I leave that challenge up to you.
|
||||
*
|
||||
* @class Phaser.Physics.Ninja.Tile
|
||||
* @classdesc The Ninja Physics Tile class. Based on code by Metanet Software.
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.Ninja.Body} body - The body that owns this shape.
|
||||
* @param {number} x - The x coordinate to create this shape at.
|
||||
* @param {number} y - The y coordinate to create this shape at.
|
||||
* @param {number} width - The width of this AABB.
|
||||
* @param {number} height - The height of this AABB.
|
||||
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
|
||||
*/
|
||||
Phaser.Physics.Ninja.Tile = function (body, x, y, width, height, type) {
|
||||
|
||||
if (typeof type === 'undefined') { type = Phaser.Physics.Ninja.Tile.EMPTY; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja.Body} system - A reference to the body that owns this shape.
|
||||
*/
|
||||
this.body = body;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.Ninja} system - A reference to the physics system.
|
||||
*/
|
||||
this.system = body.system;
|
||||
|
||||
/**
|
||||
* @property {number} id - The ID of this Tile.
|
||||
* @readonly
|
||||
*/
|
||||
this.id = type;
|
||||
|
||||
/**
|
||||
* @property {number} type - The type of this Tile.
|
||||
* @readonly
|
||||
*/
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} pos - The position of this object.
|
||||
*/
|
||||
this.pos = new Phaser.Point(x, y);
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} oldpos - The position of this object in the previous update.
|
||||
*/
|
||||
this.oldpos = new Phaser.Point(x, y);
|
||||
|
||||
if (this.id > 1 && this.id < 30)
|
||||
{
|
||||
// Tile Types 2 to 29 require square tile dimensions, so use the width as the base
|
||||
height = width;
|
||||
}
|
||||
|
||||
/**
|
||||
* @property {number} xw - Half the width.
|
||||
* @readonly
|
||||
*/
|
||||
this.xw = Math.abs(width / 2);
|
||||
|
||||
/**
|
||||
* @property {number} xw - Half the height.
|
||||
* @readonly
|
||||
*/
|
||||
this.yw = Math.abs(height / 2);
|
||||
|
||||
/**
|
||||
* @property {number} width - The width.
|
||||
* @readonly
|
||||
*/
|
||||
this.width = width;
|
||||
|
||||
/**
|
||||
* @property {number} height - The height.
|
||||
* @readonly
|
||||
*/
|
||||
this.height = height;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Point} velocity - The velocity of this object.
|
||||
*/
|
||||
this.velocity = new Phaser.Point();
|
||||
|
||||
/**
|
||||
* @property {number} signx - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.signx = 0;
|
||||
|
||||
/**
|
||||
* @property {number} signy - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.signy = 0;
|
||||
|
||||
/**
|
||||
* @property {number} sx - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.sx = 0;
|
||||
|
||||
/**
|
||||
* @property {number} sy - Internal var.
|
||||
* @private
|
||||
*/
|
||||
this.sy = 0;
|
||||
|
||||
// By default Tiles disable gravity and world bounds collision
|
||||
this.body.gravityScale = 0;
|
||||
this.body.collideWorldBounds = false;
|
||||
|
||||
if (this.id > 0)
|
||||
{
|
||||
this.setType(this.id);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.Ninja.Tile.prototype.constructor = Phaser.Physics.Ninja.Tile;
|
||||
|
||||
Phaser.Physics.Ninja.Tile.prototype = {
|
||||
|
||||
/**
|
||||
* Updates this objects position.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#integrate
|
||||
*/
|
||||
integrate: function () {
|
||||
|
||||
var px = this.pos.x;
|
||||
var py = this.pos.y;
|
||||
|
||||
this.pos.x += (this.body.drag * this.pos.x) - (this.body.drag * this.oldpos.x);
|
||||
this.pos.y += (this.body.drag * this.pos.y) - (this.body.drag * this.oldpos.y) + (this.system.gravity * this.body.gravityScale);
|
||||
|
||||
this.velocity.set(this.pos.x - px, this.pos.y - py);
|
||||
this.oldpos.set(px, py);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#collideWorldBounds
|
||||
*/
|
||||
collideWorldBounds: function () {
|
||||
|
||||
var dx = this.system.bounds.x - (this.pos.x - this.xw);
|
||||
|
||||
if (0 < dx)
|
||||
{
|
||||
this.reportCollisionVsWorld(dx, 0, 1, 0, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
dx = (this.pos.x + this.xw) - this.system.bounds.right;
|
||||
|
||||
if (0 < dx)
|
||||
{
|
||||
this.reportCollisionVsWorld(-dx, 0, -1, 0, null);
|
||||
}
|
||||
}
|
||||
|
||||
var dy = this.system.bounds.y - (this.pos.y - this.yw);
|
||||
|
||||
if (0 < dy)
|
||||
{
|
||||
this.reportCollisionVsWorld(0, dy, 0, 1, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
dy = (this.pos.y + this.yw) - this.system.bounds.bottom;
|
||||
|
||||
if (0 < dy)
|
||||
{
|
||||
this.reportCollisionVsWorld(0, -dy, 0, -1, null);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Process a world collision and apply the resulting forces.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#reportCollisionVsWorld
|
||||
* @param {number} px - The tangent velocity
|
||||
* @param {number} py - The tangent velocity
|
||||
* @param {number} dx - Collision normal
|
||||
* @param {number} dy - Collision normal
|
||||
* @param {number} obj - Object this Tile collided with
|
||||
*/
|
||||
reportCollisionVsWorld: function (px, py, dx, dy) {
|
||||
var p = this.pos;
|
||||
var o = this.oldpos;
|
||||
|
||||
// Calc velocity
|
||||
var vx = p.x - o.x;
|
||||
var vy = p.y - o.y;
|
||||
|
||||
// Find component of velocity parallel to collision normal
|
||||
var dp = (vx * dx + vy * dy);
|
||||
var nx = dp * dx; //project velocity onto collision normal
|
||||
|
||||
var ny = dp * dy; //nx,ny is normal velocity
|
||||
|
||||
var tx = vx - nx; //px,py is tangent velocity
|
||||
var ty = vy - ny;
|
||||
|
||||
// We only want to apply collision response forces if the object is travelling into, and not out of, the collision
|
||||
var b, bx, by, fx, fy;
|
||||
|
||||
if (dp < 0)
|
||||
{
|
||||
fx = tx * this.body.friction;
|
||||
fy = ty * this.body.friction;
|
||||
|
||||
b = 1 + this.body.bounce;
|
||||
|
||||
bx = (nx * b);
|
||||
by = (ny * b);
|
||||
|
||||
if (dx === 1)
|
||||
{
|
||||
this.body.touching.left = true;
|
||||
}
|
||||
else if (dx === -1)
|
||||
{
|
||||
this.body.touching.right = true;
|
||||
}
|
||||
|
||||
if (dy === 1)
|
||||
{
|
||||
this.body.touching.up = true;
|
||||
}
|
||||
else if (dy === -1)
|
||||
{
|
||||
this.body.touching.down = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Moving out of collision, do not apply forces
|
||||
bx = by = fx = fy = 0;
|
||||
}
|
||||
|
||||
// Project object out of collision
|
||||
p.x += px;
|
||||
p.y += py;
|
||||
|
||||
// Apply bounce+friction impulses which alter velocity
|
||||
o.x += px + bx + fx;
|
||||
o.y += py + by + fy;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Tiles cannot collide with the world bounds, it's up to you to keep them where you want them. But we need this API stub to satisfy the Body.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#setType
|
||||
* @param {number} id - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
|
||||
*/
|
||||
setType: function (id) {
|
||||
|
||||
if (id === Phaser.Physics.Ninja.Tile.EMPTY)
|
||||
{
|
||||
this.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
this.id = id;
|
||||
this.updateType();
|
||||
}
|
||||
|
||||
return this;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Sets this tile to be empty.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#clear
|
||||
*/
|
||||
clear: function () {
|
||||
|
||||
this.id = Phaser.Physics.Ninja.Tile.EMPTY;
|
||||
this.updateType();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Destroys this Tiles reference to Body and System.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#destroy
|
||||
*/
|
||||
destroy: function () {
|
||||
|
||||
this.body = null;
|
||||
this.system = null;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This converts a tile from implicitly-defined (via id), to explicit (via properties).
|
||||
* Don't call directly, instead of setType.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja.Tile#updateType
|
||||
* @private
|
||||
*/
|
||||
updateType: function () {
|
||||
|
||||
if (this.id === 0)
|
||||
{
|
||||
//EMPTY
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_EMPTY;
|
||||
this.signx = 0;
|
||||
this.signy = 0;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//tile is non-empty; collide
|
||||
if (this.id < Phaser.Physics.Ninja.Tile.TYPE_45DEG)
|
||||
{
|
||||
//FULL
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_FULL;
|
||||
this.signx = 0;
|
||||
this.signy = 0;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONCAVE)
|
||||
{
|
||||
// 45deg
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_45DEG;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
|
||||
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
|
||||
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
|
||||
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
this.sx = this.signx / Math.SQRT2;//get slope _unit_ normal
|
||||
this.sy = this.signy / Math.SQRT2;//since normal is (1,-1), length is sqrt(1*1 + -1*-1) = sqrt(2)
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_CONVEX)
|
||||
{
|
||||
// Concave
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONCAVE;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpn)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnn)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEnp)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONCAVEpp)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGs)
|
||||
{
|
||||
// Convex
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_CONVEX;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpn)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnn)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXnp)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.CONVEXpp)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
this.sx = 0;
|
||||
this.sy = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_22DEGb)
|
||||
{
|
||||
// 22deg small
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGs;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGs)
|
||||
{
|
||||
// 22deg big
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_22DEGb;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 1) / slen;
|
||||
this.sy = (this.signy * 2) / slen;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_67DEGb)
|
||||
{
|
||||
// 67deg small
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGs;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (this.id < Phaser.Physics.Ninja.Tile.TYPE_HALF)
|
||||
{
|
||||
// 67deg big
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_67DEGb;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = -1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 1;
|
||||
var slen = Math.sqrt(2 * 2 + 1 * 1);
|
||||
this.sx = (this.signx * 2) / slen;
|
||||
this.sy = (this.signy * 1) / slen;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Half-full tile
|
||||
this.type = Phaser.Physics.Ninja.Tile.TYPE_HALF;
|
||||
|
||||
if (this.id == Phaser.Physics.Ninja.Tile.HALFd)
|
||||
{
|
||||
this.signx = 0;
|
||||
this.signy = -1;
|
||||
this.sx = this.signx;
|
||||
this.sy = this.signy;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.HALFu)
|
||||
{
|
||||
this.signx = 0;
|
||||
this.signy = 1;
|
||||
this.sx = this.signx;
|
||||
this.sy = this.signy;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.HALFl)
|
||||
{
|
||||
this.signx = 1;
|
||||
this.signy = 0;
|
||||
this.sx = this.signx;
|
||||
this.sy = this.signy;
|
||||
}
|
||||
else if (this.id == Phaser.Physics.Ninja.Tile.HALFr)
|
||||
{
|
||||
this.signx = -1;
|
||||
this.signy = 0;
|
||||
this.sx = this.signx;
|
||||
this.sy = this.signy;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Tile#x
|
||||
* @property {number} x - The x position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
return this.pos.x - this.xw;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.pos.x = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Tile#y
|
||||
* @property {number} y - The y position.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
return this.pos.y - this.yw;
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
this.pos.y = value;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Tile#bottom
|
||||
* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "bottom", {
|
||||
|
||||
get: function () {
|
||||
return this.pos.y + this.yw;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.Ninja.Tile#right
|
||||
* @property {number} right - The right value of this Body (same as Body.x + Body.width)
|
||||
* @readonly
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.Ninja.Tile.prototype, "right", {
|
||||
|
||||
get: function () {
|
||||
return this.pos.x + this.xw;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
Phaser.Physics.Ninja.Tile.EMPTY = 0;
|
||||
Phaser.Physics.Ninja.Tile.FULL = 1;//fullAABB tile
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn = 2;//45-degree triangle, whose normal is (+ve,-ve)
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnn = 3;//(+ve,+ve)
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_45DEGnp = 4;//(-ve,+ve)
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_45DEGpp = 5;//(-ve,-ve)
|
||||
Phaser.Physics.Ninja.Tile.CONCAVEpn = 6;//1/4-circle cutout
|
||||
Phaser.Physics.Ninja.Tile.CONCAVEnn = 7;
|
||||
Phaser.Physics.Ninja.Tile.CONCAVEnp = 8;
|
||||
Phaser.Physics.Ninja.Tile.CONCAVEpp = 9;
|
||||
Phaser.Physics.Ninja.Tile.CONVEXpn = 10;//1/4/circle
|
||||
Phaser.Physics.Ninja.Tile.CONVEXnn = 11;
|
||||
Phaser.Physics.Ninja.Tile.CONVEXnp = 12;
|
||||
Phaser.Physics.Ninja.Tile.CONVEXpp = 13;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnS = 14;//22.5 degree slope
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnS = 15;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpS = 16;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppS = 17;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGpnB = 18;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnnB = 19;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGnpB = 20;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_22DEGppB = 21;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnS = 22;//67.5 degree slope
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnS = 23;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpS = 24;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppS = 25;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGpnB = 26;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnnB = 27;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGnpB = 28;
|
||||
Phaser.Physics.Ninja.Tile.SLOPE_67DEGppB = 29;
|
||||
Phaser.Physics.Ninja.Tile.HALFd = 30;//half-full tiles
|
||||
Phaser.Physics.Ninja.Tile.HALFr = 31;
|
||||
Phaser.Physics.Ninja.Tile.HALFu = 32;
|
||||
Phaser.Physics.Ninja.Tile.HALFl = 33;
|
||||
|
||||
Phaser.Physics.Ninja.Tile.TYPE_EMPTY = 0;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_FULL = 1;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_45DEG = 2;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_CONCAVE = 6;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_CONVEX = 10;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_22DEGs = 14;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_22DEGb = 18;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_67DEGs = 22;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_67DEGb = 26;
|
||||
Phaser.Physics.Ninja.Tile.TYPE_HALF = 30;
|
||||
606
src/physics/ninja/World.js
Normal file
606
src/physics/ninja/World.js
Normal file
@@ -0,0 +1,606 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Ninja Physics. The Ninja Physics system was created in Flash by Metanet Software and ported to JavaScript by Richard Davey.
|
||||
*
|
||||
* It allows for AABB and Circle to Tile collision. Tiles can be any of 34 different types, including slopes, convex and concave shapes.
|
||||
*
|
||||
* It does what it does very well, but is ripe for expansion and optimisation. Here are some features that I'd love to see the community add:
|
||||
*
|
||||
* * AABB to AABB collision
|
||||
* * AABB to Circle collision
|
||||
* * AABB and Circle 'immovable' property support
|
||||
* * n-way collision, so an AABB/Circle could pass through a tile from below and land upon it.
|
||||
* * QuadTree or spatial grid for faster Body vs. Tile Group look-ups.
|
||||
* * Optimise the internal vector math and reduce the quantity of temporary vars created.
|
||||
* * Expand Gravity and Bounce to allow for separate x/y axis values.
|
||||
* * Support Bodies linked to Sprites that don't have anchor set to 0.5
|
||||
*
|
||||
* Feel free to attempt any of the above and submit a Pull Request with your code! Be sure to include test cases proving they work.
|
||||
*
|
||||
* @class Phaser.Physics.Ninja
|
||||
* @classdesc Ninja Physics Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Game} game reference to the current game instance.
|
||||
*/
|
||||
Phaser.Physics.Ninja = function (game) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Time} time - Local reference to game.time.
|
||||
*/
|
||||
this.time = this.game.time;
|
||||
|
||||
/**
|
||||
* @property {number} gravity - The World gravity setting.
|
||||
*/
|
||||
this.gravity = 0.2;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
|
||||
*/
|
||||
this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
|
||||
|
||||
/**
|
||||
* @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
|
||||
*/
|
||||
this.maxObjects = 10;
|
||||
|
||||
/**
|
||||
* @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
|
||||
*/
|
||||
this.maxLevels = 4;
|
||||
|
||||
/**
|
||||
* @property {Phaser.QuadTree} quadTree - The world QuadTree.
|
||||
*/
|
||||
this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.Ninja.prototype.constructor = Phaser.Physics.Ninja;
|
||||
|
||||
Phaser.Physics.Ninja.prototype = {
|
||||
|
||||
/**
|
||||
* This will create a Ninja Physics AABB body on the given game object. Its dimensions will match the width and height of the object at the point it is created.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#enableAABB
|
||||
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
|
||||
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
|
||||
*/
|
||||
enableAABB: function (object, children) {
|
||||
|
||||
this.enable(object, 1, 0, 0, children);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This will create a Ninja Physics Circle body on the given game object.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#enableCircle
|
||||
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
|
||||
* @param {number} radius - The radius of the Circle.
|
||||
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
|
||||
*/
|
||||
enableCircle: function (object, radius, children) {
|
||||
|
||||
this.enable(object, 2, 0, radius, children);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This will create a Ninja Physics Tile body on the given game object. There are 34 different types of tile you can create, including 45 degree slopes,
|
||||
* convex and concave circles and more. The id parameter controls which Tile type is created, but you can also change it at run-time.
|
||||
* Note that for all degree based tile types they need to have an equal width and height. If the given object doesn't have equal width and height it will use the width.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#enableTile
|
||||
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
|
||||
* @param {number} [id=1] - The type of Tile this will use, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
|
||||
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
|
||||
*/
|
||||
enableTile: function (object, id, children) {
|
||||
|
||||
this.enable(object, 3, id, 0, children);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* This will create a Ninja Physics body on the given game object or array of game objects.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#enable
|
||||
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
|
||||
* @param {number} [type=1] - The type of Ninja shape to create. 1 = AABB, 2 = Circle or 3 = Tile.
|
||||
* @param {number} [id=1] - If this body is using a Tile shape, you can set the Tile id here, i.e. Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn, Phaser.Physics.Ninja.Tile.CONVEXpp, etc.
|
||||
* @param {number} [radius=0] - If this body is using a Circle shape this controls the radius.
|
||||
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
|
||||
*/
|
||||
enable: function (object, type, id, radius, children) {
|
||||
|
||||
if (typeof type === 'undefined') { type = 1; }
|
||||
if (typeof id === 'undefined') { id = 1; }
|
||||
if (typeof radius === 'undefined') { radius = 0; }
|
||||
if (typeof children === 'undefined') { children = true; }
|
||||
|
||||
if (Array.isArray(object))
|
||||
{
|
||||
var i = object.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
if (object[i] instanceof Phaser.Group)
|
||||
{
|
||||
// If it's a Group then we do it on the children regardless
|
||||
this.enable(object[i].children, type, id, radius, children);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.enableBody(object[i], type, id, radius);
|
||||
|
||||
if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
|
||||
{
|
||||
this.enable(object[i], type, id, radius, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (object instanceof Phaser.Group)
|
||||
{
|
||||
// If it's a Group then we do it on the children regardless
|
||||
this.enable(object.children, type, id, radius, children);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.enableBody(object, type, id, radius);
|
||||
|
||||
if (children && object.hasOwnProperty('children') && object.children.length > 0)
|
||||
{
|
||||
this.enable(object.children, type, id, radius, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a Ninja Physics body on the given game object.
|
||||
* A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#enableBody
|
||||
* @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
|
||||
*/
|
||||
enableBody: function (object, type, id, radius) {
|
||||
|
||||
if (object.hasOwnProperty('body') && object.body === null)
|
||||
{
|
||||
object.body = new Phaser.Physics.Ninja.Body(this, object, type, id, radius);
|
||||
object.anchor.set(0.5);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the size of this physics world.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#setBounds
|
||||
* @param {number} x - Top left most corner of the world.
|
||||
* @param {number} y - Top left most corner of the world.
|
||||
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
|
||||
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
|
||||
*/
|
||||
setBounds: function (x, y, width, height) {
|
||||
|
||||
this.bounds.setTo(x, y, width, height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Updates the size of this physics world to match the size of the game world.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#setBoundsToWorld
|
||||
*/
|
||||
setBoundsToWorld: function () {
|
||||
|
||||
this.bounds.setTo(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#clearTilemapLayerBodies
|
||||
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
|
||||
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
|
||||
*/
|
||||
clearTilemapLayerBodies: function (map, layer) {
|
||||
|
||||
layer = map.getLayer(layer);
|
||||
|
||||
var i = map.layers[layer].bodies.length;
|
||||
|
||||
while (i--)
|
||||
{
|
||||
map.layers[layer].bodies[i].destroy();
|
||||
}
|
||||
|
||||
map.layers[layer].bodies.length = [];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics tiles.
|
||||
* Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
|
||||
* Every time you call this method it will destroy any previously created bodies and remove them from the world.
|
||||
* Therefore understand it's a very expensive operation and not to be done in a core game update loop.
|
||||
*
|
||||
* In Ninja the Tiles have an ID from 0 to 33, where 0 is 'empty', 1 is a full tile, 2 is a 45-degree slope, etc. You can find the ID
|
||||
* list either at the very bottom of `Tile.js`, or in a handy visual reference in the `resources/Ninja Physics Debug Tiles` folder in the repository.
|
||||
* The slopeMap parameter is an array that controls how the indexes of the tiles in your tilemap data will map to the Ninja Tile IDs.
|
||||
* For example if you had 6 tiles in your tileset: Imagine the first 4 should be converted into fully solid Tiles and the other 2 are 45-degree slopes.
|
||||
* Your slopeMap array would look like this: `[ 1, 1, 1, 1, 2, 3 ]`.
|
||||
* Where each element of the array is a tile in your tilemap and the resulting Ninja Tile it should create.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#convertTilemap
|
||||
* @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
|
||||
* @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
|
||||
* @param {object} [slopeMap] - The tilemap index to Tile ID map.
|
||||
* @return {array} An array of the Phaser.Physics.Ninja.Tile objects that were created.
|
||||
*/
|
||||
convertTilemap: function (map, layer, slopeMap) {
|
||||
|
||||
layer = map.getLayer(layer);
|
||||
|
||||
// If the bodies array is already populated we need to nuke it
|
||||
this.clearTilemapLayerBodies(map, layer);
|
||||
|
||||
for (var y = 0, h = map.layers[layer].height; y < h; y++)
|
||||
{
|
||||
for (var x = 0, w = map.layers[layer].width; x < w; x++)
|
||||
{
|
||||
var tile = map.layers[layer].data[y][x];
|
||||
|
||||
if (tile && slopeMap.hasOwnProperty(tile.index))
|
||||
{
|
||||
var body = new Phaser.Physics.Ninja.Body(this, null, 3, slopeMap[tile.index], 0, tile.worldX + tile.centerX, tile.worldY + tile.centerY, tile.width, tile.height);
|
||||
|
||||
map.layers[layer].bodies.push(body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map.layers[layer].bodies;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
|
||||
* You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
|
||||
* Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
|
||||
* The second parameter can be an array of objects, of differing types.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#overlap
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
|
||||
* @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them.
|
||||
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then overlapCallback will only be called if processCallback returns true.
|
||||
* @param {object} [callbackContext] - The context in which to run the callbacks.
|
||||
* @returns {boolean} True if an overlap occured otherwise false.
|
||||
*/
|
||||
overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
|
||||
|
||||
overlapCallback = overlapCallback || null;
|
||||
processCallback = processCallback || null;
|
||||
callbackContext = callbackContext || overlapCallback;
|
||||
|
||||
this._result = false;
|
||||
this._total = 0;
|
||||
|
||||
if (Array.isArray(object2))
|
||||
{
|
||||
for (var i = 0, len = object2.length; i < len; i++)
|
||||
{
|
||||
this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
|
||||
}
|
||||
|
||||
return (this._total > 0);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
|
||||
* The second parameter can be an array of objects, of differing types.
|
||||
* The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
|
||||
* An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
|
||||
* giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
|
||||
* The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collide
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap.
|
||||
* @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
|
||||
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
|
||||
* @param {object} [callbackContext] - The context in which to run the callbacks.
|
||||
* @returns {boolean} True if a collision occured otherwise false.
|
||||
*/
|
||||
collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
|
||||
|
||||
collideCallback = collideCallback || null;
|
||||
processCallback = processCallback || null;
|
||||
callbackContext = callbackContext || collideCallback;
|
||||
|
||||
this._result = false;
|
||||
this._total = 0;
|
||||
|
||||
if (Array.isArray(object2))
|
||||
{
|
||||
for (var i = 0, len = object2.length; i < len; i++)
|
||||
{
|
||||
this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
|
||||
}
|
||||
|
||||
return (this._total > 0);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Internal collision handler.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collideHandler
|
||||
* @private
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap.
|
||||
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap. Can also be an array of objects to check.
|
||||
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
|
||||
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
|
||||
* @param {object} callbackContext - The context in which to run the callbacks.
|
||||
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
|
||||
*/
|
||||
collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
|
||||
|
||||
// Only collide valid objects
|
||||
if (typeof object2 === 'undefined' && (object1.type === Phaser.GROUP || object1.type === Phaser.EMITTER))
|
||||
{
|
||||
this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
return;
|
||||
}
|
||||
|
||||
if (object1 && object2 && object1.exists && object2.exists)
|
||||
{
|
||||
// SPRITES
|
||||
if (object1.type == Phaser.SPRITE || object1.type == Phaser.TILESPRITE)
|
||||
{
|
||||
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
|
||||
{
|
||||
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
|
||||
{
|
||||
this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.TILEMAPLAYER)
|
||||
{
|
||||
this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
|
||||
}
|
||||
}
|
||||
// GROUPS
|
||||
else if (object1.type == Phaser.GROUP)
|
||||
{
|
||||
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
|
||||
{
|
||||
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
|
||||
{
|
||||
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.TILEMAPLAYER)
|
||||
{
|
||||
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
|
||||
}
|
||||
}
|
||||
// TILEMAP LAYERS
|
||||
else if (object1.type == Phaser.TILEMAPLAYER)
|
||||
{
|
||||
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
|
||||
{
|
||||
this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
|
||||
}
|
||||
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
|
||||
{
|
||||
this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext);
|
||||
}
|
||||
}
|
||||
// EMITTER
|
||||
else if (object1.type == Phaser.EMITTER)
|
||||
{
|
||||
if (object2.type == Phaser.SPRITE || object2.type == Phaser.TILESPRITE)
|
||||
{
|
||||
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER)
|
||||
{
|
||||
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
else if (object2.type == Phaser.TILEMAPLAYER)
|
||||
{
|
||||
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* An internal function. Use Phaser.Physics.Ninja.collide instead.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collideSpriteVsSprite
|
||||
* @private
|
||||
*/
|
||||
collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
|
||||
|
||||
if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
|
||||
{
|
||||
if (collideCallback)
|
||||
{
|
||||
collideCallback.call(callbackContext, sprite1, sprite2);
|
||||
}
|
||||
|
||||
this._total++;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* An internal function. Use Phaser.Physics.Ninja.collide instead.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collideSpriteVsGroup
|
||||
* @private
|
||||
*/
|
||||
collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
|
||||
|
||||
if (group.length === 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// What is the sprite colliding with in the quadtree?
|
||||
// this.quadTree.clear();
|
||||
|
||||
// this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
|
||||
|
||||
// this.quadTree.populate(group);
|
||||
|
||||
// this._potentials = this.quadTree.retrieve(sprite);
|
||||
|
||||
for (var i = 0, len = group.children.length; i < len; i++)
|
||||
{
|
||||
// We have our potential suspects, are they in this group?
|
||||
if (group.children[i].exists && group.children[i].body && this.separate(sprite.body, group.children[i].body, processCallback, callbackContext, overlapOnly))
|
||||
{
|
||||
if (collideCallback)
|
||||
{
|
||||
collideCallback.call(callbackContext, sprite, group.children[i]);
|
||||
}
|
||||
|
||||
this._total++;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* An internal function. Use Phaser.Physics.Ninja.collide instead.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collideGroupVsSelf
|
||||
* @private
|
||||
*/
|
||||
collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
|
||||
|
||||
if (group.length === 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var len = group.children.length;
|
||||
|
||||
for (var i = 0; i < len; i++)
|
||||
{
|
||||
for (var j = i + 1; j <= len; j++)
|
||||
{
|
||||
if (group.children[i] && group.children[j] && group.children[i].exists && group.children[j].exists)
|
||||
{
|
||||
this.collideSpriteVsSprite(group.children[i], group.children[j], collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* An internal function. Use Phaser.Physics.Ninja.collide instead.
|
||||
*
|
||||
* @method Phaser.Physics.Ninja#collideGroupVsGroup
|
||||
* @private
|
||||
*/
|
||||
collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
|
||||
|
||||
if (group1.length === 0 || group2.length === 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (var i = 0, len = group1.children.length; i < len; i++)
|
||||
{
|
||||
if (group1.children[i].exists)
|
||||
{
|
||||
this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* The core separation function to separate two physics bodies.
|
||||
* @method Phaser.Physics.Ninja#separate
|
||||
* @param {Phaser.Physics.Ninja.Body} body1 - The Body object to separate.
|
||||
* @param {Phaser.Physics.Ninja.Body} body2 - The Body object to separate.
|
||||
* @returns {boolean} Returns true if the bodies collided, otherwise false.
|
||||
*/
|
||||
separate: function (body1, body2) {
|
||||
|
||||
if (body1.type !== Phaser.Physics.NINJA || body2.type !== Phaser.Physics.NINJA)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (body1.aabb && body2.aabb)
|
||||
{
|
||||
return body1.aabb.collideAABBVsAABB(body2.aabb);
|
||||
}
|
||||
|
||||
if (body1.aabb && body2.tile)
|
||||
{
|
||||
return body1.aabb.collideAABBVsTile(body2.tile);
|
||||
}
|
||||
|
||||
if (body1.tile && body2.aabb)
|
||||
{
|
||||
return body2.aabb.collideAABBVsTile(body1.tile);
|
||||
}
|
||||
|
||||
if (body1.circle && body2.tile)
|
||||
{
|
||||
return body1.circle.collideCircleVsTile(body2.tile);
|
||||
}
|
||||
|
||||
if (body1.tile && body2.circle)
|
||||
{
|
||||
return body2.circle.collideCircleVsTile(body1.tile);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
1778
src/physics/p2/Body.js
Normal file
1778
src/physics/p2/Body.js
Normal file
File diff suppressed because it is too large
Load Diff
427
src/physics/p2/BodyDebug.js
Normal file
427
src/physics/p2/BodyDebug.js
Normal file
@@ -0,0 +1,427 @@
|
||||
/**
|
||||
* @author George https://github.com/georgiee
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Draws a P2 Body to a Graphics instance for visual debugging.
|
||||
* Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead.
|
||||
* So use sparingly and rarely (if ever) in production code.
|
||||
*
|
||||
* @class Phaser.Physics.P2.BodyDebug
|
||||
* @classdesc Physics Body Debug Constructor
|
||||
* @constructor
|
||||
* @extends Phaser.Group
|
||||
* @param {Phaser.Game} game - Game reference to the currently running game.
|
||||
* @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
|
||||
* @param {object} settings - Settings object.
|
||||
*/
|
||||
Phaser.Physics.P2.BodyDebug = function(game, body, settings) {
|
||||
|
||||
Phaser.Group.call(this, game);
|
||||
|
||||
/**
|
||||
* @property {object} defaultSettings - Default debug settings.
|
||||
* @private
|
||||
*/
|
||||
var defaultSettings = {
|
||||
pixelsPerLengthUnit: 20,
|
||||
debugPolygons: false,
|
||||
lineWidth: 1,
|
||||
alpha: 0.5
|
||||
};
|
||||
|
||||
this.settings = Phaser.Utils.extend(defaultSettings, settings);
|
||||
|
||||
/**
|
||||
* @property {number} ppu - Pixels per Length Unit.
|
||||
*/
|
||||
this.ppu = this.settings.pixelsPerLengthUnit;
|
||||
this.ppu = -1 * this.ppu;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
|
||||
*/
|
||||
this.body = body;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Graphics} canvas - The canvas to render the debug info to.
|
||||
*/
|
||||
this.canvas = new Phaser.Graphics(game);
|
||||
|
||||
this.canvas.alpha = this.settings.alpha;
|
||||
|
||||
this.add(this.canvas);
|
||||
|
||||
this.draw();
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype);
|
||||
Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug;
|
||||
|
||||
Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, {
|
||||
|
||||
/**
|
||||
* Core update.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#update
|
||||
*/
|
||||
update: function() {
|
||||
|
||||
this.updateSpriteTransform();
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Core update.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform
|
||||
*/
|
||||
updateSpriteTransform: function() {
|
||||
|
||||
this.position.x = this.body.position[0] * this.ppu;
|
||||
this.position.y = this.body.position[1] * this.ppu;
|
||||
|
||||
return this.rotation = this.body.angle;
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws the P2 shapes to the Graphics object.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#draw
|
||||
*/
|
||||
draw: function() {
|
||||
|
||||
var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1;
|
||||
obj = this.body;
|
||||
sprite = this.canvas;
|
||||
sprite.clear();
|
||||
color = parseInt(this.randomPastelHex(), 16);
|
||||
lineColor = 0xff0000;
|
||||
lw = this.lineWidth;
|
||||
|
||||
if (obj instanceof p2.Body && obj.shapes.length)
|
||||
{
|
||||
var l = obj.shapes.length;
|
||||
|
||||
i = 0;
|
||||
|
||||
while (i !== l)
|
||||
{
|
||||
child = obj.shapes[i];
|
||||
offset = obj.shapeOffsets[i];
|
||||
angle = obj.shapeAngles[i];
|
||||
offset = offset || 0;
|
||||
angle = angle || 0;
|
||||
|
||||
if (child instanceof p2.Circle)
|
||||
{
|
||||
this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw);
|
||||
}
|
||||
else if (child instanceof p2.Convex)
|
||||
{
|
||||
verts = [];
|
||||
vrot = p2.vec2.create();
|
||||
|
||||
for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j)
|
||||
{
|
||||
v = child.vertices[j];
|
||||
p2.vec2.rotate(vrot, v, angle);
|
||||
verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]);
|
||||
}
|
||||
|
||||
this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]);
|
||||
}
|
||||
else if (child instanceof p2.Plane)
|
||||
{
|
||||
this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle);
|
||||
}
|
||||
else if (child instanceof p2.Line)
|
||||
{
|
||||
this.drawLine(sprite, child.length * this.ppu, lineColor, lw);
|
||||
}
|
||||
else if (child instanceof p2.Rectangle)
|
||||
{
|
||||
this.drawRectangle(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws the P2 shapes to the Graphics object.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#draw
|
||||
*/
|
||||
drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) {
|
||||
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0x000000; }
|
||||
|
||||
g.lineStyle(lineWidth, color, 1);
|
||||
g.beginFill(fillColor);
|
||||
g.drawRect(x - w / 2, y - h / 2, w, h);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a P2 Circle shape.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#drawCircle
|
||||
*/
|
||||
drawCircle: function(g, x, y, angle, radius, color, lineWidth) {
|
||||
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0xffffff; }
|
||||
g.lineStyle(lineWidth, 0x000000, 1);
|
||||
g.beginFill(color, 1.0);
|
||||
g.drawCircle(x, y, -radius);
|
||||
g.endFill();
|
||||
g.moveTo(x, y);
|
||||
g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle));
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a P2 Line shape.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#drawCircle
|
||||
*/
|
||||
drawLine: function(g, len, color, lineWidth) {
|
||||
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0x000000; }
|
||||
|
||||
g.lineStyle(lineWidth * 5, color, 1);
|
||||
g.moveTo(-len / 2, 0);
|
||||
g.lineTo(len / 2, 0);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a P2 Convex shape.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#drawConvex
|
||||
*/
|
||||
drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) {
|
||||
|
||||
var colors, i, v, v0, v1, x, x0, x1, y, y0, y1;
|
||||
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0x000000; }
|
||||
|
||||
if (!debug)
|
||||
{
|
||||
g.lineStyle(lineWidth, color, 1);
|
||||
g.beginFill(fillColor);
|
||||
i = 0;
|
||||
|
||||
while (i !== verts.length)
|
||||
{
|
||||
v = verts[i];
|
||||
x = v[0];
|
||||
y = v[1];
|
||||
|
||||
if (i === 0)
|
||||
{
|
||||
g.moveTo(x, -y);
|
||||
}
|
||||
else
|
||||
{
|
||||
g.lineTo(x, -y);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
g.endFill();
|
||||
|
||||
if (verts.length > 2)
|
||||
{
|
||||
g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]);
|
||||
return g.lineTo(verts[0][0], -verts[0][1]);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
colors = [0xff0000, 0x00ff00, 0x0000ff];
|
||||
i = 0;
|
||||
|
||||
while (i !== verts.length + 1)
|
||||
{
|
||||
v0 = verts[i % verts.length];
|
||||
v1 = verts[(i + 1) % verts.length];
|
||||
x0 = v0[0];
|
||||
y0 = v0[1];
|
||||
x1 = v1[0];
|
||||
y1 = v1[1];
|
||||
g.lineStyle(lineWidth, colors[i % colors.length], 1);
|
||||
g.moveTo(x0, -y0);
|
||||
g.lineTo(x1, -y1);
|
||||
g.drawCircle(x0, -y0, lineWidth * 2);
|
||||
i++;
|
||||
}
|
||||
|
||||
g.lineStyle(lineWidth, 0x000000, 1);
|
||||
return g.drawCircle(offset[0], offset[1], lineWidth * 2);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a P2 Path.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#drawPath
|
||||
*/
|
||||
drawPath: function(g, path, color, fillColor, lineWidth) {
|
||||
|
||||
var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y;
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0x000000; }
|
||||
|
||||
g.lineStyle(lineWidth, color, 1);
|
||||
|
||||
if (typeof fillColor === "number")
|
||||
{
|
||||
g.beginFill(fillColor);
|
||||
}
|
||||
|
||||
lastx = null;
|
||||
lasty = null;
|
||||
i = 0;
|
||||
|
||||
while (i < path.length)
|
||||
{
|
||||
v = path[i];
|
||||
x = v[0];
|
||||
y = v[1];
|
||||
|
||||
if (x !== lastx || y !== lasty)
|
||||
{
|
||||
if (i === 0)
|
||||
{
|
||||
g.moveTo(x, y);
|
||||
}
|
||||
else
|
||||
{
|
||||
p1x = lastx;
|
||||
p1y = lasty;
|
||||
p2x = x;
|
||||
p2y = y;
|
||||
p3x = path[(i + 1) % path.length][0];
|
||||
p3y = path[(i + 1) % path.length][1];
|
||||
area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y));
|
||||
|
||||
if (area !== 0)
|
||||
{
|
||||
g.lineTo(x, y);
|
||||
}
|
||||
}
|
||||
lastx = x;
|
||||
lasty = y;
|
||||
}
|
||||
|
||||
i++;
|
||||
|
||||
}
|
||||
|
||||
if (typeof fillColor === "number")
|
||||
{
|
||||
g.endFill();
|
||||
}
|
||||
|
||||
if (path.length > 2 && typeof fillColor === "number")
|
||||
{
|
||||
g.moveTo(path[path.length - 1][0], path[path.length - 1][1]);
|
||||
g.lineTo(path[0][0], path[0][1]);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Draws a P2 Plane shape.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#drawPlane
|
||||
*/
|
||||
drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) {
|
||||
|
||||
var max, xd, yd;
|
||||
if (typeof lineWidth === 'undefined') { lineWidth = 1; }
|
||||
if (typeof color === 'undefined') { color = 0xffffff; }
|
||||
|
||||
g.lineStyle(lineWidth, lineColor, 11);
|
||||
g.beginFill(color);
|
||||
max = maxLength;
|
||||
|
||||
g.moveTo(x0, -x1);
|
||||
xd = x0 + Math.cos(angle) * this.game.width;
|
||||
yd = x1 + Math.sin(angle) * this.game.height;
|
||||
g.lineTo(xd, -yd);
|
||||
|
||||
g.moveTo(x0, -x1);
|
||||
xd = x0 + Math.cos(angle) * -this.game.width;
|
||||
yd = x1 + Math.sin(angle) * -this.game.height;
|
||||
g.lineTo(xd, -yd);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Picks a random pastel color.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#randomPastelHex
|
||||
*/
|
||||
randomPastelHex: function() {
|
||||
|
||||
var blue, green, mix, red;
|
||||
mix = [255, 255, 255];
|
||||
|
||||
red = Math.floor(Math.random() * 256);
|
||||
green = Math.floor(Math.random() * 256);
|
||||
blue = Math.floor(Math.random() * 256);
|
||||
|
||||
red = Math.floor((red + 3 * mix[0]) / 4);
|
||||
green = Math.floor((green + 3 * mix[1]) / 4);
|
||||
blue = Math.floor((blue + 3 * mix[2]) / 4);
|
||||
|
||||
return this.rgbToHex(red, green, blue);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Converts from RGB to Hex.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#rgbToHex
|
||||
*/
|
||||
rgbToHex: function(r, g, b) {
|
||||
return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
|
||||
},
|
||||
|
||||
/**
|
||||
* Component to hex conversion.
|
||||
*
|
||||
* @method Phaser.Physics.P2.BodyDebug#componentToHex
|
||||
*/
|
||||
componentToHex: function(c) {
|
||||
|
||||
var hex;
|
||||
hex = c.toString(16);
|
||||
|
||||
if (hex.len === 2)
|
||||
{
|
||||
return hex;
|
||||
}
|
||||
else
|
||||
{
|
||||
return hex + '0';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
21
src/physics/p2/CollisionGroup.js
Normal file
21
src/physics/p2/CollisionGroup.js
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Collision Group
|
||||
*
|
||||
* @class Phaser.Physics.P2.CollisionGroup
|
||||
* @classdesc Physics Collision Group Constructor
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.Physics.P2.CollisionGroup = function (bitmask) {
|
||||
|
||||
/**
|
||||
* @property {number} mask - The CollisionGroup bitmask.
|
||||
*/
|
||||
this.mask = bitmask;
|
||||
|
||||
};
|
||||
64
src/physics/p2/ContactMaterial.js
Normal file
64
src/physics/p2/ContactMaterial.js
Normal file
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Defines a physics material
|
||||
*
|
||||
* @class Phaser.Physics.P2.ContactMaterial
|
||||
* @classdesc Physics ContactMaterial Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2.Material} materialA
|
||||
* @param {Phaser.Physics.P2.Material} materialB
|
||||
* @param {object} [options]
|
||||
*/
|
||||
Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) {
|
||||
|
||||
/**
|
||||
* @property {number} id - The contact material identifier.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2.Material} materialB - First second participating in the contact material.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [friction=0.3] - Friction to use in the contact of these two materials.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
|
||||
*/
|
||||
|
||||
p2.ContactMaterial.call(this, materialA, materialB, options);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype);
|
||||
Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial;
|
||||
40
src/physics/p2/DistanceConstraint.js
Normal file
40
src/physics/p2/DistanceConstraint.js
Normal file
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A constraint that tries to keep the distance between two bodies constant.
|
||||
*
|
||||
* @class Phaser.Physics.P2.DistanceConstraint
|
||||
* @classdesc Physics DistanceConstraint Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {number} distance - The distance to keep between the bodies.
|
||||
* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
|
||||
*/
|
||||
Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, maxForce) {
|
||||
|
||||
if (typeof distance === 'undefined') { distance = 100; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
distance = world.pxm(distance);
|
||||
|
||||
p2.DistanceConstraint.call(this, bodyA, bodyB, distance, {maxForce: maxForce});
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype);
|
||||
Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint;
|
||||
233
src/physics/p2/FixtureList.js
Normal file
233
src/physics/p2/FixtureList.js
Normal file
@@ -0,0 +1,233 @@
|
||||
/* jshint noarg: false */
|
||||
|
||||
/**
|
||||
* @author Georgios Kaleadis https://github.com/georgiee
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Allow to access a list of created fixture (coming from Body#addPhaserPolygon)
|
||||
* which itself parse the input from PhysicsEditor with the custom phaser exporter.
|
||||
* You can access fixtures of a Body by a group index or even by providing a fixture Key.
|
||||
|
||||
* You can set the fixture key and also the group index for a fixture in PhysicsEditor.
|
||||
* This gives you the power to create a complex body built of many fixtures and modify them
|
||||
* during runtime (to remove parts, set masks, categories & sensor properties)
|
||||
*
|
||||
* @class Phaser.Physics.P2.FixtureList
|
||||
* @classdesc Collection for generated P2 fixtures
|
||||
* @constructor
|
||||
* @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon)
|
||||
*/
|
||||
Phaser.Physics.P2.FixtureList = function (list) {
|
||||
|
||||
if (!Array.isArray(list))
|
||||
{
|
||||
list = [list];
|
||||
}
|
||||
|
||||
this.rawList = list;
|
||||
this.init();
|
||||
this.parse(this.rawList);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.FixtureList.prototype = {
|
||||
|
||||
/**
|
||||
* @method Phaser.Physics.P2.FixtureList#init
|
||||
*/
|
||||
init: function () {
|
||||
|
||||
/**
|
||||
* @property {object} namedFixtures - Collect all fixtures with a key
|
||||
* @private
|
||||
*/
|
||||
this.namedFixtures = {};
|
||||
|
||||
/**
|
||||
* @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group
|
||||
* @private
|
||||
*/
|
||||
this.groupedFixtures = [];
|
||||
|
||||
/**
|
||||
* @property {Array} allFixtures - This is a list of everything in this collection
|
||||
* @private
|
||||
*/
|
||||
this.allFixtures = [];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Physics.P2.FixtureList#setCategory
|
||||
* @param {number} bit - The bit to set as the collision group.
|
||||
* @param {string} fixtureKey - Only apply to the fixture with the given key.
|
||||
*/
|
||||
setCategory: function (bit, fixtureKey) {
|
||||
|
||||
var setter = function(fixture) {
|
||||
fixture.collisionGroup = bit;
|
||||
};
|
||||
|
||||
this.getFixtures(fixtureKey).forEach(setter);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Physics.P2.FixtureList#setMask
|
||||
* @param {number} bit - The bit to set as the collision mask
|
||||
* @param {string} fixtureKey - Only apply to the fixture with the given key
|
||||
*/
|
||||
setMask: function (bit, fixtureKey) {
|
||||
|
||||
var setter = function(fixture) {
|
||||
fixture.collisionMask = bit;
|
||||
};
|
||||
|
||||
this.getFixtures(fixtureKey).forEach(setter);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Physics.P2.FixtureList#setSensor
|
||||
* @param {boolean} value - sensor true or false
|
||||
* @param {string} fixtureKey - Only apply to the fixture with the given key
|
||||
*/
|
||||
setSensor: function (value, fixtureKey) {
|
||||
|
||||
var setter = function(fixture) {
|
||||
fixture.sensor = value;
|
||||
};
|
||||
|
||||
this.getFixtures(fixtureKey).forEach(setter);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* @method Phaser.Physics.P2.FixtureList#setMaterial
|
||||
* @param {Object} material - The contact material for a fixture
|
||||
* @param {string} fixtureKey - Only apply to the fixture with the given key
|
||||
*/
|
||||
setMaterial: function (material, fixtureKey) {
|
||||
|
||||
var setter = function(fixture) {
|
||||
fixture.material = material;
|
||||
};
|
||||
|
||||
this.getFixtures(fixtureKey).forEach(setter);
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Accessor to get either a list of specified fixtures by key or the whole fixture list
|
||||
*
|
||||
* @method Phaser.Physics.P2.FixtureList#getFixtures
|
||||
* @param {array} keys - A list of fixture keys
|
||||
*/
|
||||
getFixtures: function (keys) {
|
||||
|
||||
var fixtures = [];
|
||||
|
||||
if (keys)
|
||||
{
|
||||
if (!(keys instanceof Array))
|
||||
{
|
||||
keys = [keys];
|
||||
}
|
||||
|
||||
var self = this;
|
||||
keys.forEach(function(key) {
|
||||
if (self.namedFixtures[key])
|
||||
{
|
||||
fixtures.push(self.namedFixtures[key]);
|
||||
}
|
||||
});
|
||||
|
||||
return this.flatten(fixtures);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
return this.allFixtures;
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Accessor to get either a single fixture by its key.
|
||||
*
|
||||
* @method Phaser.Physics.P2.FixtureList#getFixtureByKey
|
||||
* @param {string} key - The key of the fixture.
|
||||
*/
|
||||
getFixtureByKey: function (key) {
|
||||
|
||||
return this.namedFixtures[key];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Accessor to get a group of fixtures by its group index.
|
||||
*
|
||||
* @method Phaser.Physics.P2.FixtureList#getGroup
|
||||
* @param {number} groupID - The group index.
|
||||
*/
|
||||
getGroup: function (groupID) {
|
||||
|
||||
return this.groupedFixtures[groupID];
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon
|
||||
*
|
||||
* @method Phaser.Physics.P2.FixtureList#parse
|
||||
*/
|
||||
parse: function () {
|
||||
|
||||
var key, value, _ref, _results;
|
||||
_ref = this.rawList;
|
||||
_results = [];
|
||||
|
||||
for (key in _ref)
|
||||
{
|
||||
value = _ref[key];
|
||||
|
||||
if (!isNaN(key - 0))
|
||||
{
|
||||
this.groupedFixtures[key] = this.groupedFixtures[key] || [];
|
||||
this.groupedFixtures[key] = this.groupedFixtures[key].concat(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.namedFixtures[key] = this.flatten(value);
|
||||
}
|
||||
|
||||
_results.push(this.allFixtures = this.flatten(this.groupedFixtures));
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
/**
|
||||
* A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons.
|
||||
*
|
||||
* @method Phaser.Physics.P2.FixtureList#flatten
|
||||
* @param {array} array - The array to flatten. Notice: This will happen recursive not shallow.
|
||||
*/
|
||||
flatten: function (array) {
|
||||
|
||||
var result, self;
|
||||
result = [];
|
||||
self = arguments.callee;
|
||||
|
||||
array.forEach(function(item) {
|
||||
return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item]));
|
||||
});
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
41
src/physics/p2/GearConstraint.js
Normal file
41
src/physics/p2/GearConstraint.js
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
|
||||
*
|
||||
* @class Phaser.Physics.P2.GearConstraint
|
||||
* @classdesc Physics GearConstraint Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {number} [angle=0] - The relative angle
|
||||
* @param {number} [ratio=1] - The gear ratio.
|
||||
*/
|
||||
Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) {
|
||||
|
||||
if (typeof angle === 'undefined') { angle = 0; }
|
||||
if (typeof ratio === 'undefined') { ratio = 1; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
var options = { angle: angle, ratio: ratio };
|
||||
|
||||
p2.GearConstraint.call(this, bodyA, bodyB, options);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype);
|
||||
Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint;
|
||||
63
src/physics/p2/InversePointProxy.js
Normal file
63
src/physics/p2/InversePointProxy.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set.
|
||||
*
|
||||
* @class Phaser.Physics.P2.InversePointProxy
|
||||
* @classdesc InversePointProxy
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {any} destination - The object to bind to.
|
||||
*/
|
||||
Phaser.Physics.P2.InversePointProxy = function (world, destination) {
|
||||
|
||||
this.world = world;
|
||||
this.destination = destination;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy;
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.P2.InversePointProxy#x
|
||||
* @property {number} x - The x property of this InversePointProxy.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.destination[0];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.destination[0] = this.world.pxm(-value);
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.P2.InversePointProxy#y
|
||||
* @property {number} y - The y property of this InversePointProxy.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.destination[1];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.destination[1] = this.world.pxm(-value);
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
45
src/physics/p2/LockConstraint.js
Normal file
45
src/physics/p2/LockConstraint.js
Normal file
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Locks the relative position between two bodies.
|
||||
*
|
||||
* @class Phaser.Physics.P2.LockConstraint
|
||||
* @classdesc Physics LockConstraint Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
|
||||
* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
|
||||
*/
|
||||
Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) {
|
||||
|
||||
if (typeof offset === 'undefined') { offset = [0, 0]; }
|
||||
if (typeof angle === 'undefined') { angle = 0; }
|
||||
if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ];
|
||||
|
||||
var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce };
|
||||
|
||||
p2.LockConstraint.call(this, bodyA, bodyB, options);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype);
|
||||
Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint;
|
||||
27
src/physics/p2/Material.js
Normal file
27
src/physics/p2/Material.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* \o/ ~ "Because I'm a Material girl"
|
||||
*
|
||||
* @class Phaser.Physics.P2.Material
|
||||
* @classdesc Physics Material Constructor
|
||||
* @constructor
|
||||
*/
|
||||
Phaser.Physics.P2.Material = function (name) {
|
||||
|
||||
/**
|
||||
* @property {string} name - The user defined name given to this Material.
|
||||
* @default
|
||||
*/
|
||||
this.name = name;
|
||||
|
||||
p2.Material.call(this);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype);
|
||||
Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material;
|
||||
63
src/physics/p2/PointProxy.js
Normal file
63
src/physics/p2/PointProxy.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays.
|
||||
*
|
||||
* @class Phaser.Physics.P2.PointProxy
|
||||
* @classdesc PointProxy
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {any} destination - The object to bind to.
|
||||
*/
|
||||
Phaser.Physics.P2.PointProxy = function (world, destination) {
|
||||
|
||||
this.world = world;
|
||||
this.destination = destination;
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy;
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.P2.PointProxy#x
|
||||
* @property {number} x - The x property of this PointProxy.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.destination[0];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.destination[0] = this.world.pxm(value);
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
/**
|
||||
* @name Phaser.Physics.P2.PointProxy#y
|
||||
* @property {number} y - The y property of this PointProxy.
|
||||
*/
|
||||
Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", {
|
||||
|
||||
get: function () {
|
||||
|
||||
return this.destination[1];
|
||||
|
||||
},
|
||||
|
||||
set: function (value) {
|
||||
|
||||
this.destination[1] = this.world.pxm(value);
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
50
src/physics/p2/PrismaticConstraint.js
Normal file
50
src/physics/p2/PrismaticConstraint.js
Normal file
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
|
||||
*
|
||||
* @class Phaser.Physics.P2.PrismaticConstraint
|
||||
* @classdesc Physics PrismaticConstraint Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
|
||||
* @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
|
||||
*/
|
||||
Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
|
||||
|
||||
if (typeof lockRotation === 'undefined') { lockRotation = true; }
|
||||
if (typeof anchorA === 'undefined') { anchorA = [0, 0]; }
|
||||
if (typeof anchorB === 'undefined') { anchorB = [0, 0]; }
|
||||
if (typeof axis === 'undefined') { axis = [0, 0]; }
|
||||
if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ];
|
||||
anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ];
|
||||
|
||||
var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation };
|
||||
|
||||
p2.PrismaticConstraint.call(this, bodyA, bodyB, options);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype);
|
||||
Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint;
|
||||
43
src/physics/p2/RevoluteConstraint.js
Normal file
43
src/physics/p2/RevoluteConstraint.js
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Connects two bodies at given offset points, letting them rotate relative to each other around this point.
|
||||
* The pivot points are given in world (pixel) coordinates.
|
||||
*
|
||||
* @class Phaser.Physics.P2.RevoluteConstraint
|
||||
* @classdesc Physics RevoluteConstraint Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
|
||||
*/
|
||||
Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce) {
|
||||
|
||||
if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; }
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ];
|
||||
pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ];
|
||||
|
||||
p2.RevoluteConstraint.call(this, bodyA, pivotA, bodyB, pivotB, {maxForce: maxForce});
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype);
|
||||
Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
|
||||
73
src/physics/p2/Spring.js
Normal file
73
src/physics/p2/Spring.js
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* @author Richard Davey <rich@photonstorm.com>
|
||||
* @copyright 2014 Photon Storm Ltd.
|
||||
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
|
||||
*
|
||||
* @class Phaser.Physics.P2.Spring
|
||||
* @classdesc Physics Spring Constructor
|
||||
* @constructor
|
||||
* @param {Phaser.Physics.P2} world - A reference to the P2 World.
|
||||
* @param {p2.Body} bodyA - First connected body.
|
||||
* @param {p2.Body} bodyB - Second connected body.
|
||||
* @param {number} [restLength=1] - Rest length of the spring. A number > 0.
|
||||
* @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
|
||||
* @param {number} [damping=1] - Damping of the spring. A number >= 0.
|
||||
* @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
* @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
|
||||
*/
|
||||
Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
|
||||
|
||||
/**
|
||||
* @property {Phaser.Game} game - Local reference to game.
|
||||
*/
|
||||
this.game = world.game;
|
||||
|
||||
/**
|
||||
* @property {Phaser.Physics.P2} world - Local reference to P2 World.
|
||||
*/
|
||||
this.world = world;
|
||||
|
||||
if (typeof restLength === 'undefined') { restLength = 1; }
|
||||
if (typeof stiffness === 'undefined') { stiffness = 100; }
|
||||
if (typeof damping === 'undefined') { damping = 1; }
|
||||
|
||||
restLength = world.pxm(restLength);
|
||||
|
||||
var options = {
|
||||
restLength: restLength,
|
||||
stiffness: stiffness,
|
||||
damping: damping
|
||||
};
|
||||
|
||||
if (typeof worldA !== 'undefined' && worldA !== null)
|
||||
{
|
||||
options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ];
|
||||
}
|
||||
|
||||
if (typeof worldB !== 'undefined' && worldB !== null)
|
||||
{
|
||||
options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ];
|
||||
}
|
||||
|
||||
if (typeof localA !== 'undefined' && localA !== null)
|
||||
{
|
||||
options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ];
|
||||
}
|
||||
|
||||
if (typeof localB !== 'undefined' && localB !== null)
|
||||
{
|
||||
options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ];
|
||||
}
|
||||
|
||||
p2.Spring.call(this, bodyA, bodyB, options);
|
||||
|
||||
};
|
||||
|
||||
Phaser.Physics.P2.Spring.prototype = Object.create(p2.Spring.prototype);
|
||||
Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
|
||||
1876
src/physics/p2/World.js
Normal file
1876
src/physics/p2/World.js
Normal file
File diff suppressed because it is too large
Load Diff
11485
src/physics/p2/p2.js
Normal file
11485
src/physics/p2/p2.js
Normal file
File diff suppressed because it is too large
Load Diff
63
src/pixi/InteractionData.js
Normal file
63
src/pixi/InteractionData.js
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
/**
|
||||
* Holds all information related to an Interaction event
|
||||
*
|
||||
* @class InteractionData
|
||||
* @constructor
|
||||
*/
|
||||
PIXI.InteractionData = function()
|
||||
{
|
||||
/**
|
||||
* This point stores the global coords of where the touch/mouse event happened
|
||||
*
|
||||
* @property global
|
||||
* @type Point
|
||||
*/
|
||||
this.global = new PIXI.Point();
|
||||
|
||||
// this is here for legacy... but will remove
|
||||
this.local = new PIXI.Point();
|
||||
|
||||
/**
|
||||
* The target Sprite that was interacted with
|
||||
*
|
||||
* @property target
|
||||
* @type Sprite
|
||||
*/
|
||||
this.target = null;
|
||||
|
||||
/**
|
||||
* When passed to an event handler, this will be the original DOM Event that was captured
|
||||
*
|
||||
* @property originalEvent
|
||||
* @type Event
|
||||
*/
|
||||
this.originalEvent = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* This will return the local coordinates of the specified displayObject for this InteractionData
|
||||
*
|
||||
* @method getLocalPosition
|
||||
* @param displayObject {DisplayObject} The DisplayObject that you would like the local coords off
|
||||
* @return {Point} A point containing the coordinates of the InteractionData position relative to the DisplayObject
|
||||
*/
|
||||
PIXI.InteractionData.prototype.getLocalPosition = function(displayObject)
|
||||
{
|
||||
var worldTransform = displayObject.worldTransform;
|
||||
var global = this.global;
|
||||
|
||||
// do a cheeky transform to get the mouse coords;
|
||||
var a00 = worldTransform.a, a01 = worldTransform.b, a02 = worldTransform.tx,
|
||||
a10 = worldTransform.c, a11 = worldTransform.d, a12 = worldTransform.ty,
|
||||
id = 1 / (a00 * a11 + a01 * -a10);
|
||||
// set the mouse coords...
|
||||
return new PIXI.Point(a11 * id * global.x + -a01 * id * global.y + (a12 * a01 - a02 * a11) * id,
|
||||
a00 * id * global.y + -a10 * id * global.x + (-a12 * a00 + a02 * a10) * id);
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.InteractionData.prototype.constructor = PIXI.InteractionData;
|
||||
715
src/pixi/InteractionManager.js
Normal file
715
src/pixi/InteractionManager.js
Normal file
@@ -0,0 +1,715 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
/**
|
||||
* The interaction manager deals with mouse and touch events. Any DisplayObject can be interactive
|
||||
* if its interactive parameter is set to true
|
||||
* This manager also supports multitouch.
|
||||
*
|
||||
* @class InteractionManager
|
||||
* @constructor
|
||||
* @param stage {Stage} The stage to handle interactions
|
||||
*/
|
||||
PIXI.InteractionManager = function(stage)
|
||||
{
|
||||
/**
|
||||
* a reference to the stage
|
||||
*
|
||||
* @property stage
|
||||
* @type Stage
|
||||
*/
|
||||
this.stage = stage;
|
||||
|
||||
/**
|
||||
* the mouse data
|
||||
*
|
||||
* @property mouse
|
||||
* @type InteractionData
|
||||
*/
|
||||
this.mouse = new PIXI.InteractionData();
|
||||
|
||||
/**
|
||||
* an object that stores current touches (InteractionData) by id reference
|
||||
*
|
||||
* @property touchs
|
||||
* @type Object
|
||||
*/
|
||||
this.touchs = {};
|
||||
|
||||
// helpers
|
||||
this.tempPoint = new PIXI.Point();
|
||||
|
||||
/**
|
||||
*
|
||||
* @property mouseoverEnabled
|
||||
* @type Boolean
|
||||
* @default
|
||||
*/
|
||||
this.mouseoverEnabled = true;
|
||||
|
||||
/**
|
||||
* tiny little interactiveData pool !
|
||||
*
|
||||
* @property pool
|
||||
* @type Array
|
||||
*/
|
||||
this.pool = [];
|
||||
|
||||
/**
|
||||
* An array containing all the iterative items from the our interactive tree
|
||||
* @property interactiveItems
|
||||
* @type Array
|
||||
* @private
|
||||
*
|
||||
*/
|
||||
this.interactiveItems = [];
|
||||
|
||||
/**
|
||||
* Our canvas
|
||||
* @property interactionDOMElement
|
||||
* @type HTMLCanvasElement
|
||||
* @private
|
||||
*/
|
||||
this.interactionDOMElement = null;
|
||||
|
||||
//this will make it so that you dont have to call bind all the time
|
||||
this.onMouseMove = this.onMouseMove.bind( this );
|
||||
this.onMouseDown = this.onMouseDown.bind(this);
|
||||
this.onMouseOut = this.onMouseOut.bind(this);
|
||||
this.onMouseUp = this.onMouseUp.bind(this);
|
||||
|
||||
this.onTouchStart = this.onTouchStart.bind(this);
|
||||
this.onTouchEnd = this.onTouchEnd.bind(this);
|
||||
this.onTouchMove = this.onTouchMove.bind(this);
|
||||
|
||||
this.last = 0;
|
||||
|
||||
/**
|
||||
* The css style of the cursor that is being used
|
||||
* @property currentCursorStyle
|
||||
* @type String
|
||||
*
|
||||
*/
|
||||
this.currentCursorStyle = 'inherit';
|
||||
|
||||
/**
|
||||
* Is set to true when the mouse is moved out of the canvas
|
||||
* @property mouseOut
|
||||
* @type Boolean
|
||||
*
|
||||
*/
|
||||
this.mouseOut = false;
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.InteractionManager.prototype.constructor = PIXI.InteractionManager;
|
||||
|
||||
/**
|
||||
* Collects an interactive sprite recursively to have their interactions managed
|
||||
*
|
||||
* @method collectInteractiveSprite
|
||||
* @param displayObject {DisplayObject} the displayObject to collect
|
||||
* @param iParent {DisplayObject} the display object's parent
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.collectInteractiveSprite = function(displayObject, iParent)
|
||||
{
|
||||
var children = displayObject.children;
|
||||
var length = children.length;
|
||||
|
||||
// make an interaction tree... {item.__interactiveParent}
|
||||
for (var i = length-1; i >= 0; i--)
|
||||
{
|
||||
var child = children[i];
|
||||
|
||||
// push all interactive bits
|
||||
if(child._interactive)
|
||||
{
|
||||
iParent.interactiveChildren = true;
|
||||
//child.__iParent = iParent;
|
||||
this.interactiveItems.push(child);
|
||||
|
||||
if(child.children.length > 0)
|
||||
{
|
||||
this.collectInteractiveSprite(child, child);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
child.__iParent = null;
|
||||
|
||||
if(child.children.length > 0)
|
||||
{
|
||||
this.collectInteractiveSprite(child, iParent);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the target for event delegation
|
||||
*
|
||||
* @method setTarget
|
||||
* @param target {WebGLRenderer|CanvasRenderer} the renderer to bind events to
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.setTarget = function(target)
|
||||
{
|
||||
this.target = target;
|
||||
|
||||
//check if the dom element has been set. If it has don't do anything
|
||||
if( this.interactionDOMElement === null ) {
|
||||
|
||||
this.setTargetDomElement( target.view );
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* Sets the DOM element which will receive mouse/touch events. This is useful for when you have other DOM
|
||||
* elements on top of the renderers Canvas element. With this you'll be able to delegate another DOM element
|
||||
* to receive those events
|
||||
*
|
||||
* @method setTargetDomElement
|
||||
* @param domElement {DOMElement} the DOM element which will receive mouse and touch events
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.setTargetDomElement = function(domElement)
|
||||
{
|
||||
|
||||
this.removeEvents();
|
||||
|
||||
|
||||
if (window.navigator.msPointerEnabled)
|
||||
{
|
||||
// time to remove some of that zoom in ja..
|
||||
domElement.style['-ms-content-zooming'] = 'none';
|
||||
domElement.style['-ms-touch-action'] = 'none';
|
||||
|
||||
// DO some window specific touch!
|
||||
}
|
||||
|
||||
this.interactionDOMElement = domElement;
|
||||
|
||||
domElement.addEventListener('mousemove', this.onMouseMove, true);
|
||||
domElement.addEventListener('mousedown', this.onMouseDown, true);
|
||||
domElement.addEventListener('mouseout', this.onMouseOut, true);
|
||||
|
||||
// aint no multi touch just yet!
|
||||
domElement.addEventListener('touchstart', this.onTouchStart, true);
|
||||
domElement.addEventListener('touchend', this.onTouchEnd, true);
|
||||
domElement.addEventListener('touchmove', this.onTouchMove, true);
|
||||
|
||||
window.addEventListener('mouseup', this.onMouseUp, true);
|
||||
};
|
||||
|
||||
|
||||
PIXI.InteractionManager.prototype.removeEvents = function()
|
||||
{
|
||||
if(!this.interactionDOMElement)return;
|
||||
|
||||
this.interactionDOMElement.style['-ms-content-zooming'] = '';
|
||||
this.interactionDOMElement.style['-ms-touch-action'] = '';
|
||||
|
||||
this.interactionDOMElement.removeEventListener('mousemove', this.onMouseMove, true);
|
||||
this.interactionDOMElement.removeEventListener('mousedown', this.onMouseDown, true);
|
||||
this.interactionDOMElement.removeEventListener('mouseout', this.onMouseOut, true);
|
||||
|
||||
// aint no multi touch just yet!
|
||||
this.interactionDOMElement.removeEventListener('touchstart', this.onTouchStart, true);
|
||||
this.interactionDOMElement.removeEventListener('touchend', this.onTouchEnd, true);
|
||||
this.interactionDOMElement.removeEventListener('touchmove', this.onTouchMove, true);
|
||||
|
||||
this.interactionDOMElement = null;
|
||||
|
||||
window.removeEventListener('mouseup', this.onMouseUp, true);
|
||||
};
|
||||
|
||||
/**
|
||||
* updates the state of interactive objects
|
||||
*
|
||||
* @method update
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.update = function()
|
||||
{
|
||||
if(!this.target)return;
|
||||
|
||||
// frequency of 30fps??
|
||||
var now = Date.now();
|
||||
var diff = now - this.last;
|
||||
diff = (diff * PIXI.INTERACTION_FREQUENCY ) / 1000;
|
||||
if(diff < 1)return;
|
||||
this.last = now;
|
||||
|
||||
var i = 0;
|
||||
|
||||
// ok.. so mouse events??
|
||||
// yes for now :)
|
||||
// OPTIMISE - how often to check??
|
||||
if(this.dirty)
|
||||
{
|
||||
this.dirty = false;
|
||||
|
||||
var len = this.interactiveItems.length;
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
this.interactiveItems[i].interactiveChildren = false;
|
||||
}
|
||||
|
||||
this.interactiveItems = [];
|
||||
|
||||
if(this.stage.interactive)this.interactiveItems.push(this.stage);
|
||||
// go through and collect all the objects that are interactive..
|
||||
this.collectInteractiveSprite(this.stage, this.stage);
|
||||
}
|
||||
|
||||
// loop through interactive objects!
|
||||
var length = this.interactiveItems.length;
|
||||
var cursor = 'inherit';
|
||||
var over = false;
|
||||
|
||||
for (i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
|
||||
// OPTIMISATION - only calculate every time if the mousemove function exists..
|
||||
// OK so.. does the object have any other interactive functions?
|
||||
// hit-test the clip!
|
||||
// if(item.mouseover || item.mouseout || item.buttonMode)
|
||||
// {
|
||||
// ok so there are some functions so lets hit test it..
|
||||
item.__hit = this.hitTest(item, this.mouse);
|
||||
this.mouse.target = item;
|
||||
// ok so deal with interactions..
|
||||
// looks like there was a hit!
|
||||
if(item.__hit && !over)
|
||||
{
|
||||
if(item.buttonMode) cursor = item.defaultCursor;
|
||||
|
||||
if(!item.interactiveChildren)over = true;
|
||||
|
||||
if(!item.__isOver)
|
||||
{
|
||||
if(item.mouseover)item.mouseover(this.mouse);
|
||||
item.__isOver = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(item.__isOver)
|
||||
{
|
||||
// roll out!
|
||||
if(item.mouseout)item.mouseout(this.mouse);
|
||||
item.__isOver = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if( this.currentCursorStyle !== cursor )
|
||||
{
|
||||
this.currentCursorStyle = cursor;
|
||||
this.interactionDOMElement.style.cursor = cursor;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when the mouse moves across the renderer element
|
||||
*
|
||||
* @method onMouseMove
|
||||
* @param event {Event} The DOM event of the mouse moving
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onMouseMove = function(event)
|
||||
{
|
||||
this.mouse.originalEvent = event || window.event; //IE uses window.event
|
||||
// TODO optimize by not check EVERY TIME! maybe half as often? //
|
||||
var rect = this.interactionDOMElement.getBoundingClientRect();
|
||||
|
||||
this.mouse.global.x = (event.clientX - rect.left) * (this.target.width / rect.width);
|
||||
this.mouse.global.y = (event.clientY - rect.top) * ( this.target.height / rect.height);
|
||||
|
||||
var length = this.interactiveItems.length;
|
||||
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
|
||||
if(item.mousemove)
|
||||
{
|
||||
//call the function!
|
||||
item.mousemove(this.mouse);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when the mouse button is pressed down on the renderer element
|
||||
*
|
||||
* @method onMouseDown
|
||||
* @param event {Event} The DOM event of a mouse button being pressed down
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onMouseDown = function(event)
|
||||
{
|
||||
this.mouse.originalEvent = event || window.event; //IE uses window.event
|
||||
|
||||
if(PIXI.AUTO_PREVENT_DEFAULT)this.mouse.originalEvent.preventDefault();
|
||||
|
||||
// loop through interaction tree...
|
||||
// hit test each item! ->
|
||||
// get interactive items under point??
|
||||
//stage.__i
|
||||
var length = this.interactiveItems.length;
|
||||
|
||||
// while
|
||||
// hit test
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
|
||||
if(item.mousedown || item.click)
|
||||
{
|
||||
item.__mouseIsDown = true;
|
||||
item.__hit = this.hitTest(item, this.mouse);
|
||||
|
||||
if(item.__hit)
|
||||
{
|
||||
//call the function!
|
||||
if(item.mousedown)item.mousedown(this.mouse);
|
||||
item.__isDown = true;
|
||||
|
||||
// just the one!
|
||||
if(!item.interactiveChildren)break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when the mouse button is moved out of the renderer element
|
||||
*
|
||||
* @method onMouseOut
|
||||
* @param event {Event} The DOM event of a mouse button being moved out
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onMouseOut = function()
|
||||
{
|
||||
var length = this.interactiveItems.length;
|
||||
|
||||
this.interactionDOMElement.style.cursor = 'inherit';
|
||||
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
if(item.__isOver)
|
||||
{
|
||||
this.mouse.target = item;
|
||||
if(item.mouseout)item.mouseout(this.mouse);
|
||||
item.__isOver = false;
|
||||
}
|
||||
}
|
||||
|
||||
this.mouseOut = true;
|
||||
|
||||
// move the mouse to an impossible position
|
||||
this.mouse.global.x = -10000;
|
||||
this.mouse.global.y = -10000;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when the mouse button is released on the renderer element
|
||||
*
|
||||
* @method onMouseUp
|
||||
* @param event {Event} The DOM event of a mouse button being released
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onMouseUp = function(event)
|
||||
{
|
||||
|
||||
this.mouse.originalEvent = event || window.event; //IE uses window.event
|
||||
|
||||
var length = this.interactiveItems.length;
|
||||
var up = false;
|
||||
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
|
||||
item.__hit = this.hitTest(item, this.mouse);
|
||||
|
||||
if(item.__hit && !up)
|
||||
{
|
||||
//call the function!
|
||||
if(item.mouseup)
|
||||
{
|
||||
item.mouseup(this.mouse);
|
||||
}
|
||||
if(item.__isDown)
|
||||
{
|
||||
if(item.click)item.click(this.mouse);
|
||||
}
|
||||
|
||||
if(!item.interactiveChildren)up = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(item.__isDown)
|
||||
{
|
||||
if(item.mouseupoutside)item.mouseupoutside(this.mouse);
|
||||
}
|
||||
}
|
||||
|
||||
item.__isDown = false;
|
||||
//}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests if the current mouse coordinates hit a sprite
|
||||
*
|
||||
* @method hitTest
|
||||
* @param item {DisplayObject} The displayObject to test for a hit
|
||||
* @param interactionData {InteractionData} The interactionData object to update in the case there is a hit
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.hitTest = function(item, interactionData)
|
||||
{
|
||||
var global = interactionData.global;
|
||||
|
||||
if( !item.worldVisible )return false;
|
||||
|
||||
// temp fix for if the element is in a non visible
|
||||
|
||||
var isSprite = (item instanceof PIXI.Sprite),
|
||||
worldTransform = item.worldTransform,
|
||||
a00 = worldTransform.a, a01 = worldTransform.b, a02 = worldTransform.tx,
|
||||
a10 = worldTransform.c, a11 = worldTransform.d, a12 = worldTransform.ty,
|
||||
id = 1 / (a00 * a11 + a01 * -a10),
|
||||
x = a11 * id * global.x + -a01 * id * global.y + (a12 * a01 - a02 * a11) * id,
|
||||
y = a00 * id * global.y + -a10 * id * global.x + (-a12 * a00 + a02 * a10) * id;
|
||||
|
||||
interactionData.target = item;
|
||||
|
||||
//a sprite or display object with a hit area defined
|
||||
if(item.hitArea && item.hitArea.contains) {
|
||||
if(item.hitArea.contains(x, y)) {
|
||||
//if(isSprite)
|
||||
interactionData.target = item;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
// a sprite with no hitarea defined
|
||||
else if(isSprite)
|
||||
{
|
||||
var width = item.texture.frame.width,
|
||||
height = item.texture.frame.height,
|
||||
x1 = -width * item.anchor.x,
|
||||
y1;
|
||||
|
||||
if(x > x1 && x < x1 + width)
|
||||
{
|
||||
y1 = -height * item.anchor.y;
|
||||
|
||||
if(y > y1 && y < y1 + height)
|
||||
{
|
||||
// set the target property if a hit is true!
|
||||
interactionData.target = item;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var length = item.children.length;
|
||||
|
||||
for (var i = 0; i < length; i++)
|
||||
{
|
||||
var tempItem = item.children[i];
|
||||
var hit = this.hitTest(tempItem, interactionData);
|
||||
if(hit)
|
||||
{
|
||||
// hmm.. TODO SET CORRECT TARGET?
|
||||
interactionData.target = item;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when a touch is moved across the renderer element
|
||||
*
|
||||
* @method onTouchMove
|
||||
* @param event {Event} The DOM event of a touch moving across the renderer view
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onTouchMove = function(event)
|
||||
{
|
||||
var rect = this.interactionDOMElement.getBoundingClientRect();
|
||||
var changedTouches = event.changedTouches;
|
||||
var touchData;
|
||||
var i = 0;
|
||||
|
||||
for (i = 0; i < changedTouches.length; i++)
|
||||
{
|
||||
var touchEvent = changedTouches[i];
|
||||
touchData = this.touchs[touchEvent.identifier];
|
||||
touchData.originalEvent = event || window.event;
|
||||
|
||||
// update the touch position
|
||||
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
|
||||
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
|
||||
if(navigator.isCocoonJS) {
|
||||
touchData.global.x = touchEvent.clientX;
|
||||
touchData.global.y = touchEvent.clientY;
|
||||
}
|
||||
}
|
||||
|
||||
var length = this.interactiveItems.length;
|
||||
for (i = 0; i < length; i++)
|
||||
{
|
||||
var item = this.interactiveItems[i];
|
||||
if(item.touchmove)
|
||||
item.touchmove(touchData);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when a touch is started on the renderer element
|
||||
*
|
||||
* @method onTouchStart
|
||||
* @param event {Event} The DOM event of a touch starting on the renderer view
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onTouchStart = function(event)
|
||||
{
|
||||
var rect = this.interactionDOMElement.getBoundingClientRect();
|
||||
|
||||
if(PIXI.AUTO_PREVENT_DEFAULT)event.preventDefault();
|
||||
|
||||
var changedTouches = event.changedTouches;
|
||||
for (var i=0; i < changedTouches.length; i++)
|
||||
{
|
||||
var touchEvent = changedTouches[i];
|
||||
|
||||
var touchData = this.pool.pop();
|
||||
if(!touchData)touchData = new PIXI.InteractionData();
|
||||
|
||||
touchData.originalEvent = event || window.event;
|
||||
|
||||
this.touchs[touchEvent.identifier] = touchData;
|
||||
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
|
||||
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
|
||||
if(navigator.isCocoonJS) {
|
||||
touchData.global.x = touchEvent.clientX;
|
||||
touchData.global.y = touchEvent.clientY;
|
||||
}
|
||||
|
||||
var length = this.interactiveItems.length;
|
||||
|
||||
for (var j = 0; j < length; j++)
|
||||
{
|
||||
var item = this.interactiveItems[j];
|
||||
|
||||
if(item.touchstart || item.tap)
|
||||
{
|
||||
item.__hit = this.hitTest(item, touchData);
|
||||
|
||||
if(item.__hit)
|
||||
{
|
||||
//call the function!
|
||||
if(item.touchstart)item.touchstart(touchData);
|
||||
item.__isDown = true;
|
||||
item.__touchData = touchData;
|
||||
|
||||
if(!item.interactiveChildren)break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Is called when a touch is ended on the renderer element
|
||||
*
|
||||
* @method onTouchEnd
|
||||
* @param event {Event} The DOM event of a touch ending on the renderer view
|
||||
* @private
|
||||
*/
|
||||
PIXI.InteractionManager.prototype.onTouchEnd = function(event)
|
||||
{
|
||||
//this.mouse.originalEvent = event || window.event; //IE uses window.event
|
||||
var rect = this.interactionDOMElement.getBoundingClientRect();
|
||||
var changedTouches = event.changedTouches;
|
||||
|
||||
for (var i=0; i < changedTouches.length; i++)
|
||||
{
|
||||
var touchEvent = changedTouches[i];
|
||||
var touchData = this.touchs[touchEvent.identifier];
|
||||
var up = false;
|
||||
touchData.global.x = (touchEvent.clientX - rect.left) * (this.target.width / rect.width);
|
||||
touchData.global.y = (touchEvent.clientY - rect.top) * (this.target.height / rect.height);
|
||||
if(navigator.isCocoonJS) {
|
||||
touchData.global.x = touchEvent.clientX;
|
||||
touchData.global.y = touchEvent.clientY;
|
||||
}
|
||||
|
||||
var length = this.interactiveItems.length;
|
||||
for (var j = 0; j < length; j++)
|
||||
{
|
||||
var item = this.interactiveItems[j];
|
||||
var itemTouchData = item.__touchData; // <-- Here!
|
||||
item.__hit = this.hitTest(item, touchData);
|
||||
|
||||
if(itemTouchData === touchData)
|
||||
{
|
||||
// so this one WAS down...
|
||||
touchData.originalEvent = event || window.event;
|
||||
// hitTest??
|
||||
|
||||
if(item.touchend || item.tap)
|
||||
{
|
||||
if(item.__hit && !up)
|
||||
{
|
||||
if(item.touchend)item.touchend(touchData);
|
||||
if(item.__isDown)
|
||||
{
|
||||
if(item.tap)item.tap(touchData);
|
||||
}
|
||||
|
||||
if(!item.interactiveChildren)up = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(item.__isDown)
|
||||
{
|
||||
if(item.touchendoutside)item.touchendoutside(touchData);
|
||||
}
|
||||
}
|
||||
|
||||
item.__isDown = false;
|
||||
}
|
||||
|
||||
item.__touchData = null;
|
||||
|
||||
}
|
||||
/*
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
*/
|
||||
}
|
||||
// remove the touch..
|
||||
this.pool.push(touchData);
|
||||
this.touchs[touchEvent.identifier] = null;
|
||||
}
|
||||
};
|
||||
7
src/pixi/Intro.js
Normal file
7
src/pixi/Intro.js
Normal file
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
(function(){
|
||||
|
||||
var root = this;
|
||||
15
src/pixi/Outro.js
Normal file
15
src/pixi/Outro.js
Normal file
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
if (typeof exports !== 'undefined') {
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
exports = module.exports = PIXI;
|
||||
}
|
||||
exports.PIXI = PIXI;
|
||||
} else if (typeof define !== 'undefined' && define.amd) {
|
||||
define('PIXI', (function() { return root.PIXI = PIXI; })() );
|
||||
} else {
|
||||
root.PIXI = PIXI;
|
||||
}
|
||||
}).call(this);
|
||||
54
src/pixi/Pixi.js
Normal file
54
src/pixi/Pixi.js
Normal file
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
/**
|
||||
* @module PIXI
|
||||
*/
|
||||
var PIXI = PIXI || {};
|
||||
|
||||
/*
|
||||
*
|
||||
* This file contains a lot of pixi consts which are used across the rendering engine
|
||||
* @class Consts
|
||||
*/
|
||||
PIXI.WEBGL_RENDERER = 0;
|
||||
PIXI.CANVAS_RENDERER = 1;
|
||||
|
||||
// useful for testing against if your lib is using pixi.
|
||||
PIXI.VERSION = "v1.5.2";
|
||||
|
||||
// the various blend modes supported by pixi
|
||||
PIXI.blendModes = {
|
||||
NORMAL:0,
|
||||
ADD:1,
|
||||
MULTIPLY:2,
|
||||
SCREEN:3,
|
||||
OVERLAY:4,
|
||||
DARKEN:5,
|
||||
LIGHTEN:6,
|
||||
COLOR_DODGE:7,
|
||||
COLOR_BURN:8,
|
||||
HARD_LIGHT:9,
|
||||
SOFT_LIGHT:10,
|
||||
DIFFERENCE:11,
|
||||
EXCLUSION:12,
|
||||
HUE:13,
|
||||
SATURATION:14,
|
||||
COLOR:15,
|
||||
LUMINOSITY:16
|
||||
};
|
||||
|
||||
// the scale modes
|
||||
PIXI.scaleModes = {
|
||||
DEFAULT:0,
|
||||
LINEAR:0,
|
||||
NEAREST:1
|
||||
};
|
||||
|
||||
// interaction frequency
|
||||
PIXI.INTERACTION_FREQUENCY = 30;
|
||||
PIXI.AUTO_PREVENT_DEFAULT = true;
|
||||
|
||||
PIXI.RAD_TO_DEG = 180 / Math.PI;
|
||||
PIXI.DEG_TO_RAD = Math.PI / 180;
|
||||
74
src/pixi/core/Circle.js
Normal file
74
src/pixi/core/Circle.js
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* @author Chad Engler <chad@pantherdev.com>
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Circle object can be used to specify a hit area for displayObjects
|
||||
*
|
||||
* @class Circle
|
||||
* @constructor
|
||||
* @param x {Number} The X coordinate of the center of this circle
|
||||
* @param y {Number} The Y coordinate of the center of this circle
|
||||
* @param radius {Number} The radius of the circle
|
||||
*/
|
||||
PIXI.Circle = function(x, y, radius)
|
||||
{
|
||||
/**
|
||||
* @property x
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.x = x || 0;
|
||||
|
||||
/**
|
||||
* @property y
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.y = y || 0;
|
||||
|
||||
/**
|
||||
* @property radius
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.radius = radius || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a clone of this Circle instance
|
||||
*
|
||||
* @method clone
|
||||
* @return {Circle} a copy of the polygon
|
||||
*/
|
||||
PIXI.Circle.prototype.clone = function()
|
||||
{
|
||||
return new PIXI.Circle(this.x, this.y, this.radius);
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks whether the x, and y coordinates passed to this function are contained within this circle
|
||||
*
|
||||
* @method contains
|
||||
* @param x {Number} The X coordinate of the point to test
|
||||
* @param y {Number} The Y coordinate of the point to test
|
||||
* @return {Boolean} Whether the x/y coordinates are within this polygon
|
||||
*/
|
||||
PIXI.Circle.prototype.contains = function(x, y)
|
||||
{
|
||||
if(this.radius <= 0)
|
||||
return false;
|
||||
|
||||
var dx = (this.x - x),
|
||||
dy = (this.y - y),
|
||||
r2 = this.radius * this.radius;
|
||||
|
||||
dx *= dx;
|
||||
dy *= dy;
|
||||
|
||||
return (dx + dy <= r2);
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.Circle.prototype.constructor = PIXI.Circle;
|
||||
|
||||
92
src/pixi/core/Ellipse.js
Normal file
92
src/pixi/core/Ellipse.js
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* @author Chad Engler <chad@pantherdev.com>
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Ellipse object can be used to specify a hit area for displayObjects
|
||||
*
|
||||
* @class Ellipse
|
||||
* @constructor
|
||||
* @param x {Number} The X coordinate of the upper-left corner of the framing rectangle of this ellipse
|
||||
* @param y {Number} The Y coordinate of the upper-left corner of the framing rectangle of this ellipse
|
||||
* @param width {Number} The overall width of this ellipse
|
||||
* @param height {Number} The overall height of this ellipse
|
||||
*/
|
||||
PIXI.Ellipse = function(x, y, width, height)
|
||||
{
|
||||
/**
|
||||
* @property x
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.x = x || 0;
|
||||
|
||||
/**
|
||||
* @property y
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.y = y || 0;
|
||||
|
||||
/**
|
||||
* @property width
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.width = width || 0;
|
||||
|
||||
/**
|
||||
* @property height
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.height = height || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a clone of this Ellipse instance
|
||||
*
|
||||
* @method clone
|
||||
* @return {Ellipse} a copy of the ellipse
|
||||
*/
|
||||
PIXI.Ellipse.prototype.clone = function()
|
||||
{
|
||||
return new PIXI.Ellipse(this.x, this.y, this.width, this.height);
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks whether the x and y coordinates passed to this function are contained within this ellipse
|
||||
*
|
||||
* @method contains
|
||||
* @param x {Number} The X coordinate of the point to test
|
||||
* @param y {Number} The Y coordinate of the point to test
|
||||
* @return {Boolean} Whether the x/y coords are within this ellipse
|
||||
*/
|
||||
PIXI.Ellipse.prototype.contains = function(x, y)
|
||||
{
|
||||
if(this.width <= 0 || this.height <= 0)
|
||||
return false;
|
||||
|
||||
//normalize the coords to an ellipse with center 0,0
|
||||
var normx = ((x - this.x) / this.width),
|
||||
normy = ((y - this.y) / this.height);
|
||||
|
||||
normx *= normx;
|
||||
normy *= normy;
|
||||
|
||||
return (normx + normy <= 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the framing rectangle of the ellipse as a PIXI.Rectangle object
|
||||
*
|
||||
* @method getBounds
|
||||
* @return {Rectangle} the framing rectangle
|
||||
*/
|
||||
PIXI.Ellipse.prototype.getBounds = function()
|
||||
{
|
||||
return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.Ellipse.prototype.constructor = PIXI.Ellipse;
|
||||
92
src/pixi/core/Matrix.js
Normal file
92
src/pixi/core/Matrix.js
Normal file
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
PIXI.determineMatrixArrayType = function() {
|
||||
return (typeof Float32Array !== 'undefined') ? Float32Array : Array;
|
||||
};
|
||||
|
||||
/*
|
||||
* @class Matrix2
|
||||
* The Matrix2 class will choose the best type of array to use between
|
||||
* a regular javascript Array and a Float32Array if the latter is available
|
||||
*
|
||||
*/
|
||||
PIXI.Matrix2 = PIXI.determineMatrixArrayType();
|
||||
|
||||
/*
|
||||
* @class Matrix
|
||||
* The Matrix class is now an object, which makes it a lot faster,
|
||||
* here is a representation of it :
|
||||
* | a | b | tx|
|
||||
* | c | c | ty|
|
||||
* | 0 | 0 | 1 |
|
||||
*
|
||||
*/
|
||||
PIXI.Matrix = function()
|
||||
{
|
||||
this.a = 1;
|
||||
this.b = 0;
|
||||
this.c = 0;
|
||||
this.d = 1;
|
||||
this.tx = 0;
|
||||
this.ty = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a pixi matrix object based on the array given as a parameter
|
||||
*
|
||||
* @method fromArray
|
||||
* @param array {Array} The array that the matrix will be filled with
|
||||
*/
|
||||
PIXI.Matrix.prototype.fromArray = function(array)
|
||||
{
|
||||
this.a = array[0];
|
||||
this.b = array[1];
|
||||
this.c = array[3];
|
||||
this.d = array[4];
|
||||
this.tx = array[2];
|
||||
this.ty = array[5];
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates an array from the current Matrix object
|
||||
*
|
||||
* @method toArray
|
||||
* @param transpose {Boolean} Whether we need to transpose the matrix or not
|
||||
* @return array {Array} the newly created array which contains the matrix
|
||||
*/
|
||||
PIXI.Matrix.prototype.toArray = function(transpose)
|
||||
{
|
||||
if(!this.array) this.array = new Float32Array(9);
|
||||
var array = this.array;
|
||||
|
||||
if(transpose)
|
||||
{
|
||||
this.array[0] = this.a;
|
||||
this.array[1] = this.c;
|
||||
this.array[2] = 0;
|
||||
this.array[3] = this.b;
|
||||
this.array[4] = this.d;
|
||||
this.array[5] = 0;
|
||||
this.array[6] = this.tx;
|
||||
this.array[7] = this.ty;
|
||||
this.array[8] = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.array[0] = this.a;
|
||||
this.array[1] = this.b;
|
||||
this.array[2] = this.tx;
|
||||
this.array[3] = this.c;
|
||||
this.array[4] = this.d;
|
||||
this.array[5] = this.ty;
|
||||
this.array[6] = 0;
|
||||
this.array[7] = 0;
|
||||
this.array[8] = 1;
|
||||
}
|
||||
|
||||
return array;//[this.a, this.b, this.tx, this.c, this.d, this.ty, 0, 0, 1];
|
||||
};
|
||||
|
||||
PIXI.identityMatrix = new PIXI.Matrix();
|
||||
49
src/pixi/core/Point.js
Normal file
49
src/pixi/core/Point.js
Normal file
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/ @Doormat23
|
||||
*/
|
||||
|
||||
/**
|
||||
* The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
|
||||
*
|
||||
* @class Point
|
||||
* @constructor
|
||||
* @param x {Number} position of the point on the x axis
|
||||
* @param y {Number} position of the point on the y axis
|
||||
*/
|
||||
PIXI.Point = function(x, y)
|
||||
{
|
||||
/**
|
||||
* @property x
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.x = x || 0;
|
||||
|
||||
/**
|
||||
* @property y
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.y = y || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a clone of this point
|
||||
*
|
||||
* @method clone
|
||||
* @return {Point} a copy of the point
|
||||
*/
|
||||
PIXI.Point.prototype.clone = function()
|
||||
{
|
||||
return new PIXI.Point(this.x, this.y);
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.Point.prototype.constructor = PIXI.Point;
|
||||
|
||||
PIXI.Point.prototype.set = function(x, y)
|
||||
{
|
||||
this.x = x || 0;
|
||||
this.y = y || ( (y !== 0) ? this.x : 0 ) ;
|
||||
};
|
||||
|
||||
77
src/pixi/core/Polygon.js
Normal file
77
src/pixi/core/Polygon.js
Normal file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* @author Adrien Brault <adrien.brault@gmail.com>
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Polygon
|
||||
* @constructor
|
||||
* @param points* {Array<Point>|Array<Number>|Point...|Number...} This can be an array of Points that form the polygon,
|
||||
* a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be
|
||||
* all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the
|
||||
* arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are
|
||||
* Numbers.
|
||||
*/
|
||||
PIXI.Polygon = function(points)
|
||||
{
|
||||
//if points isn't an array, use arguments as the array
|
||||
if(!(points instanceof Array))
|
||||
points = Array.prototype.slice.call(arguments);
|
||||
|
||||
//if this is a flat array of numbers, convert it to points
|
||||
if(typeof points[0] === 'number') {
|
||||
var p = [];
|
||||
for(var i = 0, il = points.length; i < il; i+=2) {
|
||||
p.push(
|
||||
new PIXI.Point(points[i], points[i + 1])
|
||||
);
|
||||
}
|
||||
|
||||
points = p;
|
||||
}
|
||||
|
||||
this.points = points;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a clone of this polygon
|
||||
*
|
||||
* @method clone
|
||||
* @return {Polygon} a copy of the polygon
|
||||
*/
|
||||
PIXI.Polygon.prototype.clone = function()
|
||||
{
|
||||
var points = [];
|
||||
for (var i=0; i<this.points.length; i++) {
|
||||
points.push(this.points[i].clone());
|
||||
}
|
||||
|
||||
return new PIXI.Polygon(points);
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks whether the x and y coordinates passed to this function are contained within this polygon
|
||||
*
|
||||
* @method contains
|
||||
* @param x {Number} The X coordinate of the point to test
|
||||
* @param y {Number} The Y coordinate of the point to test
|
||||
* @return {Boolean} Whether the x/y coordinates are within this polygon
|
||||
*/
|
||||
PIXI.Polygon.prototype.contains = function(x, y)
|
||||
{
|
||||
var inside = false;
|
||||
|
||||
// use some raycasting to test hits
|
||||
// https://github.com/substack/point-in-polygon/blob/master/index.js
|
||||
for(var i = 0, j = this.points.length - 1; i < this.points.length; j = i++) {
|
||||
var xi = this.points[i].x, yi = this.points[i].y,
|
||||
xj = this.points[j].x, yj = this.points[j].y,
|
||||
intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
|
||||
|
||||
if(intersect) inside = !inside;
|
||||
}
|
||||
|
||||
return inside;
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.Polygon.prototype.constructor = PIXI.Polygon;
|
||||
87
src/pixi/core/Rectangle.js
Normal file
87
src/pixi/core/Rectangle.js
Normal file
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* @author Mat Groves http://matgroves.com/
|
||||
*/
|
||||
|
||||
/**
|
||||
* the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height.
|
||||
*
|
||||
* @class Rectangle
|
||||
* @constructor
|
||||
* @param x {Number} The X coord of the upper-left corner of the rectangle
|
||||
* @param y {Number} The Y coord of the upper-left corner of the rectangle
|
||||
* @param width {Number} The overall width of this rectangle
|
||||
* @param height {Number} The overall height of this rectangle
|
||||
*/
|
||||
PIXI.Rectangle = function(x, y, width, height)
|
||||
{
|
||||
/**
|
||||
* @property x
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.x = x || 0;
|
||||
|
||||
/**
|
||||
* @property y
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.y = y || 0;
|
||||
|
||||
/**
|
||||
* @property width
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.width = width || 0;
|
||||
|
||||
/**
|
||||
* @property height
|
||||
* @type Number
|
||||
* @default 0
|
||||
*/
|
||||
this.height = height || 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a clone of this Rectangle
|
||||
*
|
||||
* @method clone
|
||||
* @return {Rectangle} a copy of the rectangle
|
||||
*/
|
||||
PIXI.Rectangle.prototype.clone = function()
|
||||
{
|
||||
return new PIXI.Rectangle(this.x, this.y, this.width, this.height);
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks whether the x and y coordinates passed to this function are contained within this Rectangle
|
||||
*
|
||||
* @method contains
|
||||
* @param x {Number} The X coordinate of the point to test
|
||||
* @param y {Number} The Y coordinate of the point to test
|
||||
* @return {Boolean} Whether the x/y coords are within this Rectangle
|
||||
*/
|
||||
PIXI.Rectangle.prototype.contains = function(x, y)
|
||||
{
|
||||
if(this.width <= 0 || this.height <= 0)
|
||||
return false;
|
||||
|
||||
var x1 = this.x;
|
||||
if(x >= x1 && x <= x1 + this.width)
|
||||
{
|
||||
var y1 = this.y;
|
||||
|
||||
if(y >= y1 && y <= y1 + this.height)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
// constructor
|
||||
PIXI.Rectangle.prototype.constructor = PIXI.Rectangle;
|
||||
|
||||
PIXI.EmptyRectangle = new PIXI.Rectangle(0,0,0,0);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user