Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

Camera Shaking Plugin for your use


CodeToWin
 Share

Recommended Posts

The question of how to shake the camera in action games has come up a few times. I wanted to learn how to create plugins for Phaser, so I made a camera shaking plugin.

 

You can see it in action here

 

You can find the code here

 

 

Modes allowed:

 

shake up and down 

shake left to right

shake both up/down, left/right with a fixed amplitude

shake both up/down, left/right with a random amplitude (up to +/- a maximum)

 

 

You can also combine increasing or decreasing amplitude with the above camera shaking modes.

 

 

This is free for you to use, abuse, or modify at your whim. Let me know what you think

Link to comment
Share on other sites

Here's mine:

'use strict';function ScreenShake(game, parent) {  Phaser.Plugin.call(this, game, parent);  this.game.shaker = this;  this.shaking = false;  this.shakeDurationMs = 0;  this.shakeStrength = 0;}ScreenShake.prototype = Object.create(Phaser.Plugin.prototype);ScreenShake.prototype.constructor = ScreenShake;ScreenShake.prototype.update = function() {  if (this.shaking) {    this.shakeDurationMs = Math.max(0, this.shakeDurationMs - this.game.time.physicsElapsedMS);    if (this.deltaX) {      this.game.camera.x -= this.deltaX;    }    if (this.deltaY) {      this.game.camera.y -= this.deltaY;    }    this.deltaX = this.game.rnd.integerInRange(-this.shakeStrength, this.shakeStrength);    this.deltaY = this.game.rnd.integerInRange(-this.shakeStrength, this.shakeStrength);    this.game.camera.x += this.deltaX;    this.game.camera.y += this.deltaY;    if (this.shakeDurationMs == 0) {      this.shaking = false;      // Reset the world and camera bounds.      this.game.world.setBounds(this.boundsCache.x, this.boundsCache.y, this.boundsCache.width, this.boundsCache.height);    }  }};ScreenShake.prototype.start = function(durationMs, strength) {  this.shaking = true;  this.shakeDurationMs = durationMs || 2000;  this.shakeStrength = strength || 5;  this.boundsCache = Phaser.Utils.extend(false, {}, this.game.world.bounds);  this.game.world.setBounds(    this.boundsCache.x - this.shakeStrength, this.boundsCache.y - this.shakeStrength,    this.boundsCache.width + this.shakeStrength, this.boundsCache.height + this.shakeStrength);};module.exports = ScreenShake;

It's built using CommonJS (hence the module.exports). One thing I really like about it is it keeps the shake centered on where the camera is supposed to be instead of drifting away over time. It also changes world bounds to accommodate the shake, if needed.

 

I'll be writing tutorials soon. :)

Link to comment
Share on other sites

  • 3 weeks later...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...