Skip to content

Instantly share code, notes, and snippets.

@jorio
Last active November 29, 2016 10:33
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 jorio/0dacc42713a569250ecaadfbc229c1a3 to your computer and use it in GitHub Desktop.
Save jorio/0dacc42713a569250ecaadfbc229c1a3 to your computer and use it in GitHub Desktop.
custom Shake implementation for Phaser 2
export class Shake {
game: Phaser.Game;
x: boolean;
y: boolean;
xoff: number;
yoff: number;
amp: number;
tween: Phaser.Tween;
constructor(game: Phaser.Game) {
this.game = game;
}
shake(amp: number, duration: number, x: boolean, y?: boolean) {
this.reset();
this.x = x;
this.y = !x && y === undefined? true: y;
this.amp = amp;
this.tween = this.game.add.tween(this);
this.tween.to({amp: 0}, duration, Phaser.Easing.Linear.None, true);
}
reset() {
this.restore();
this.xoff = 0;
this.yoff = 0;
this.amp = 0;
if (this.tween) {
this.tween.stop();
this.tween = null;
}
}
private restore() {
if (this.x) this.game.camera.x -= this.xoff;
if (this.y) this.game.camera.y -= this.yoff;
}
update() {
if (!this.amp) {
return;
}
this.restore();
if (this.x) {
this.xoff = Math.round(this.game.rnd.realInRange(-this.amp, this.amp));
this.game.camera.x += this.xoff;
}
if (this.y) {
this.yoff = Math.round(this.game.rnd.realInRange(-this.amp, this.amp));
this.game.camera.y += this.yoff;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment