Skip to content

Instantly share code, notes, and snippets.

@Problematic
Created January 17, 2015 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Problematic/5f90c42393e25ed05bea to your computer and use it in GitHub Desktop.
Save Problematic/5f90c42393e25ed05bea to your computer and use it in GitHub Desktop.
Screenshake plugin for PhaserJS
function Screenshake (game, parent) {
Phaser.Plugin.call(this, game, parent);
this.timer = this.game.time.create(false);
this.timer.start();
this.shakeCount = 0;
this.shakeAmount = 1;
this._initialBounds = this.game.camera.bounds;
this.game.camera.bounds = null;
this._cameraPosCache = [this.game.camera.x, this.game.camera.y];
}
Screenshake.prototype = Object.create(Phaser.Plugin.prototype);
Screenshake.prototype.constructor = Screenshake;
Screenshake.prototype.update = function () {
if (this.shakeCount > 0) {
var t = 2 * Math.PI * this.game.rnd.frac();
var u = this.game.rnd.frac() + this.game.rnd.frac();
var r = (u > 1 ? 2 - u : u) * this.shakeAmount;
this.game.camera.x = r * Math.cos(t);
this.game.camera.y = r * Math.sin(t);
}
};
Screenshake.prototype.shake = function (duration, amount) {
if (this.shakeCount === 0) {
this._cameraPosCache[0] = this.game.camera.x;
this._cameraPosCache[1] = this.game.camera.y;
}
this.shakeCount++;
this.shakeAmount = amount || 1;
this.timer.add(duration || 100, this.shakedown, this);
};
Screenshake.prototype.shakedown = function () {
this.shakeCount--;
if (this.shakeCount === 0) {
this.game.camera.setPosition(this._cameraPosCache[0], this._cameraPosCache[1]);
}
};
Phaser.Plugin.Screenshake = Screenshake;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment