From: MegaBrutal <code+git@megabrutal.com>
Date: Fri, 29 Dec 2017 23:25:00 +0000 (+0100)
Subject: Reuse same tween for monster shaking
X-Git-Url: http://git.megabrutal.com/?p=ld40.git;a=commitdiff_plain;h=b69fd06095d7d61ccbcd237298aeb306331991c3

Reuse same tween for monster shaking

Now one tween is created and reused to shake a monster when it is
damaged. As a side-effect, the amplitude of shaking is now constant
while it was random in the previous commit.

I decided to use one tween for a monster to avoid creating a memory
leak by leaving unused tweens in memory.

	modified:   ld40.js
---

diff --git a/ld40.js b/ld40.js
index 53e41f8..7bf03d7 100644
--- a/ld40.js
+++ b/ld40.js
@@ -32,6 +32,9 @@
             }
         }, false);
 
+        function sign(n) {
+            if (n >= 0) { return 1 } else { return -1 };
+        }
 
         class Player extends Phaser.Text {
             constructor(x, y) {
@@ -155,6 +158,7 @@
                 this.weapon = new JusticeBlaster(game, this);
                 this.weapon.bulletSpeed = SPEED_MPROJECTILE;
                 this.weapon.trackSprite(this);
+                this.shaketween = game.add.tween(this).to({ x: this.x + (sign(Math.random() - 0.5)) * 5 }, 10, Phaser.Easing.Sinusoidal.InOut, false, 0, 8, true);
             }
 
             enablePhysics() {
@@ -163,7 +167,7 @@
 
             damage(amount) {
                 super.damage(amount);
-                if (this.alive) { game.add.tween(this).to({ x: this.x + (Math.random() - 0.5) * 10 }, 10, Phaser.Easing.Sinusoidal.InOut, true, 0, 8, true); }
+                if (this.alive) { this.shaketween.start(); }
             }
 
             kill() {