Jump to content

destroy sprite after tween complete doesn't always works


rbudiharso
 Share

Recommended Posts

Anybody ever have this problem before?, In this code:

while (killedSprites.length > 0) {    var sprite = killedSprites.shift();    var tween = game.add.tween(sprite);    tween.to({ alpha: 0 }, 100, Phaser.Easing.Linear.None);    tween.onComplete.add(function () {        sprite.destroy();    });    tween.start();}

Why is it that when killedSprite has more than 1 sprites, only the first sprite gets detroyed even if the tweens are all run and complete.

Link to comment
Share on other sites

Because the 'sprite' var can only refer to one sprite and is accessible in this context by all of the tweens (rather than there being a different sprite reference for each complete event) so when all of the tweens finish, they're all trying to destroy the same sprite. You could probably fix the problem by doing it this way:

killedSprites.forEach(function(sprite) {    var tween = game.add.tween(sprite);    tween.to({ alpha: 0 }, 100, Phaser.Easing.Linear.None);    tween.onComplete.add(function () {        sprite.destroy();    });    tween.start();});// now we've done everything we need to do with the array, we can just blank itkilledSprites = [];

Now because you're using an anonymous function to perform each action, every tween has its own unique sprite reference to destroy. We can then just discard the whole array after doing it, rather than pick them off one by one.

Link to comment
Share on other sites

Unfortunately not - loops are not a context in JavaScript, but functions are. It's a common issue and not entirely easy to spot or work out if you're not aware of how context works! When you're declaring your sprite var, you're doing it in the context of the whole function and any functions within it, so it's reused each time the while loop repeats. To avoid this you need to ensure you encapsulate your variables by declaring them inside the function that the action is performed in. Tricky stuff!

Link to comment
Share on other sites

Yup, it javascript 101 about closure, this code also works, tl;dr one can use IIFE for this to works :D

while (killedSprites.length > 0) {    var sprite = killedSprites.shift();    (function (_sprite) {        var tween = game.add.tween(_sprite);        tween.to({ alpha: 0 }, 100, Phaser.Easing.Linear.None);        tween.onComplete.add(function () {            _sprite.destroy();        });        tween.start();    })(sprite);}
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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