ScreenShake.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. /**
  3. * Plugin to make screen shake FX (makes number of short camera movements).
  4. *
  5. * Usage:
  6. * in main create function:
  7. * game.plugins.screenShake = game.plugins.add(Phaser.Plugin.ScreenShake);
  8. *
  9. * in function where need to call shake FX:
  10. * game.plugins.screenShake.setup({ //if need to replace default plugin settings
  11. * shakeX: true,
  12. * shakeY: false
  13. * });
  14. * this.game.plugins.screenShake.shake(10); //pass shake count value
  15. *
  16. *
  17. *
  18. * @author Dmitry Maslov <maslov.dmitrij@gmail.com>
  19. * @copyright 2014 Dmitry Maslov
  20. * @license http://choosealicense.com/licenses/mit
  21. *
  22. */
  23. Phaser.Plugin.ScreenShake = function(game, parent){
  24. Phaser.Plugin.call(this, game, parent);
  25. //settings by default
  26. this._settings = {
  27. shakesCount: 0,
  28. shakeX: true,
  29. shakeY: true,
  30. sensCoef: 0.5
  31. };
  32. this.game.camera.bounds = null;
  33. /**
  34. * screen shake FX.
  35. */
  36. this._moveCamera = function(){
  37. if(this._settings.shakesCount > 0){
  38. var sens = this._settings.shakesCount * this._settings.sensCoef;
  39. if(this._settings.shakesCount % 2){
  40. this.game.camera.x += this._settings.shakeX ? sens : 0;
  41. this.game.camera.y += this._settings.shakeY ? sens : 0;
  42. }
  43. else{
  44. this.game.camera.x -= this._settings.shakeX ? sens : 0;
  45. this.game.camera.y -= this._settings.shakeY ? sens : 0;
  46. }
  47. this._settings.shakesCount--;
  48. if(this._settings.shakesCount === 0){
  49. this.game.camera.setPosition(0, 0);
  50. }
  51. }
  52. };
  53. };
  54. Phaser.Plugin.ScreenShake.prototype = Object.create(Phaser.Plugin.prototype);
  55. Phaser.Plugin.ScreenShake.prototype.constructor = Phaser.Plugin.ScreenShake;
  56. /**
  57. * Change default settings object values with passed object value.
  58. *
  59. * @method Phaser.Plugin.ScreenShake#setup
  60. * @param {object} [obj] - Passed object to merge
  61. */
  62. Phaser.Plugin.ScreenShake.prototype.setup = function(obj){
  63. this._settings = Phaser.Utils.extend(false, this._settings, obj);
  64. };
  65. /**
  66. * Pass value of count shakes.
  67. *
  68. * @method Phaser.Plugin.ScreenShake#shake
  69. * @param {number} [count] - Value of count shakes
  70. */
  71. Phaser.Plugin.ScreenShake.prototype.shake = function(count){
  72. this._settings.shakesCount = count;
  73. };
  74. Phaser.Plugin.ScreenShake.prototype.update = function(){
  75. this._moveCamera();
  76. };