FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

Game Mechanic: Add a Countdown Timer

One key game mechanic of video games is to add challenge to a game by making the player complete something within a certain time.

In this section we will do this with a simple count down timer.

 

 

Check the Code: what we need to know and do

Our count down timer will be visible in the top left. When it counts down to zero then it will trigger the starting of the game over state.

This mechanic using the following techniques which are covered in more detail in other parts of this book;

To add a timer to our code we will need to follow the following steps;
 
The code for a minimal example of the Adding A Timer game mechanic is shown here - https://game-mechanic-timer.glitch.me/
 
 

Going over the code:

Let's jump into the details, to look at the following groups of code;
 
    this.timeLimit = 5;
    this.timeText = game.add.text(10, 10, "0:00");
    this.timeText.fill = "#000000";
    this.timer = game.time.events.loop(1000, this.tick, this);
 
This code block; 
 
  • defines how long the time limit will be
  • adds an empty text object to the game which will be updated later
  • sets the colour of the text
  • creates a timer event object which will run the tick() function every 1000 miliseconds ( which is one second)
So we now need to look at what is in the tick() function
 
playState.tick = function () {
    this.timeLimit--;
    var minutes = Math.floor(this.timeLimit / 60);
    var seconds = this.timeLimit - (minutes * 60);
    var timeString = this.addZeros(minutes) + ":" + this.addZeros(seconds);
    this.timeText.text = timeString;
    if (this.timeLimit === 0) {
        game.state.start("gameover");
    }
};
 
We can see here that every time tick is called every second it;
  • reduces our time limit by one seconn
  • then does some formatting of the time to create a easy to read number
  • updates the text of our timer with the friendly version of the time coundown (using the addZeros() function to help it)
  • checks to see if the time is down to zero yet and if it does starts the gameover state

 When it comes to the gameover state there isn't too much new here. It is worth mentioning that here we have created a separate function to restart the game which gets called via a timer event after two seconds (2000 miliseconds.

var gameoverState = {};

gameoverState.create = function () {
    this.gameoverText = game.add.text(10, 10, "Game Over");
    this.gameoverText.fill = "#ffffff";
    game.time.events.add(2000, this.restart, this);
};

gameoverState.restart = function () {
    game.state.start("play");
};

 

 
 

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.