Introduction
Again, this is nothing groundbreaking. The countdown is initialised to “5” in
the create()
method. I’ve added a simple event to manage calling
decreaseCountdown()
every second, and this just decreases the countdown until
it hits zero - then it just removes it from the display.
create() {
// Initialise the countdown.
this.data.set('countdown', 5);
// Stash a reference to the printed countdown item.
this.textObjects['countdown'] = this.printAt(
String(this.data.get('countdown')),
16, 1,
0xFF00FF
);
// Add an event to decrease the countdown.
this.countdownTimer = this.time.addEvent({
delay: 1000,
callback: this.decreaseCountdown,
callbackScope: this,
// 1 + 4 more event actions.
repeat: 4
});
}
decreaseCountdown() {
let countdown = this.data.get('countdown');
countdown--;
if (countdown == 0) {
// Remove the countdown.
this.textObjects['countdown'].forEach(sprite => {
sprite.top.destroy();
sprite.bottom.destroy();
});
this.textObjects['countdown'] = null;
return;
}
// Update the printed countdown item.
this.data.set('countdown', countdown);
this.updateText(
this.textObjects['countdown'],
String(countdown)
);
}
But … for the sake of this demo, I’ll make a few changes to loop it around to keep on counting down from 5 to 1!
create() {
// Add an event to decrease the countdown.
this.countdownTimer = this.time.addEvent({
delay: 1000,
callback: this.decreaseCountdown,
callbackScope: this,
// Just keep on looping.
loop: true
});
}
decreaseCountdown() {
let countdown = this.data.get('countdown');
countdown--;
if (countdown == 0) {
// Restart the countdown (for demo purposes!)
countdown = 5;
}
// Update the printed countdown item.
this.data.set('countdown', countdown);
this.updateText(
this.textObjects['countdown'],
String(countdown)
);
}