Aakash Jain
Aakash Jain

Reputation: 1973

Phaser: destroying text after a fixed number of seconds

I'm using the following function in Phaser to create floating instructions that disappear after the first 5 seconds. This function is called from inside the create function.

setupText: function () {
  this.instructions = this.add.text( 510, 600, 
    'Use Arrow Keys to Move, Press Z to Fire\nClicking does both', 
    {font: '20px monospace', fill: '#fff', align: 'center'}
  );
  this.instructions.anchor.setTo(0.5, 0.5);
  this.time.events.add(5000, this.instructions.destroy, this);
},

It quickly became obvious that the timed event isn't what I'm supposed to use here, because after five seconds it causes the whole game to become unresponsive.

Being a complete beginner, I searched around for the correct way to implement such events, but I couldn't find anything.

The tutorial I'm following creates a variable holding the number of seconds the message should remain for, and then calls from update a function that destroys the text if the time limit has been reached. This seems like a bad approach to me because the checking function is called over and over from update even though it's only needed for the first 5 seconds.

So I'm looking for help on the best way to do this, and also an explanation why my code caused the entire game to stop.

Upvotes: 2

Views: 2414

Answers (1)

parchment
parchment

Reputation: 4002

The problem is that when you call this:

this.time.events.add(5000, this.instructions.destroy, this);

It calls the destroy function on the this object, which is probably your game.

To fix that, pass this.instructions instead.

this.time.events.add(5000, this.instructions.destroy, this.instructions);

Upvotes: 2

Related Questions