piotr Posted December 3, 2017 Share Posted December 3, 2017 Hi all, I want to show and hide a sprite with timers. With this code it seems that the timers are called multiple times every time and this causes the game to freeze and eventually crash. Is there a way to add timers once and them just call them when needed? Thanks Enemy.Shaker = function (game,player) { game.time.events.add(1000, this.show, this); }; Enemy.Shaker.prototype = Object.create(Phaser.Sprite.prototype); Enemy.Shaker.prototype.constructor = Enemy.Shaker; Enemy.Shaker.prototype.show = function() { this.visible = true; this.animations.play('isEnemy').onComplete.add(function() { this.game.camera.shake(0.05, 1000); game.time.events.add(1200, this.hide, this); }, this); console.log('show'); }; Enemy.Shaker.prototype.hide = function() { this.visible = false; game.time.events.add(2000, this.show, this); console.log('hide'); }; Link to comment Share on other sites More sharing options...
samme Posted December 3, 2017 Share Posted December 3, 2017 I think you're actually stacking up callbacks on the onComplete signal. That should be added only once. Link to comment Share on other sites More sharing options...
piotr Posted December 3, 2017 Author Share Posted December 3, 2017 Thanks. It makes sense but I can't figure out how to only add it once because I don't see where it is added twice. Link to comment Share on other sites More sharing options...
samme Posted December 3, 2017 Share Posted December 3, 2017 Either move onComplete.add to the constructor or keep it in show and change it to onComplete.addOnce. piotr 1 Link to comment Share on other sites More sharing options...
piotr Posted December 3, 2017 Author Share Posted December 3, 2017 Thanks! I didn't know about onComplete.addOnce. Now it works. Here's the full working code: Enemy.Shaker = function (game,player) { game.time.events.add(1000, this.show, this); }; Enemy.Shaker.prototype = Object.create(Phaser.Sprite.prototype); Enemy.Shaker.prototype.constructor = Enemy.Shaker; Enemy.Shaker.prototype.show = function() { this.visible = true; this.animations.play('isEnemy').onComplete.addOnce(function() { this.game.camera.shake(0.05, 1000); game.time.events.add(1200, this.hide, this); }, this); console.log('show'); }; Enemy.Shaker.prototype.hide = function() { this.visible = false; game.time.events.add(2000, this.show, this); console.log('hide'); }; Link to comment Share on other sites More sharing options...
Recommended Posts