Ch011 - Game Mechanic: Add a Countdown Timer

Ch011 - Game Mechanic: Add a Countdown Timer

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.

game mechanics timer

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;

Going over the code:

The code for a minimal example of the Adding A Timer game mechanic is shown here - https://jamm-labs.github.io/ggcp/game-mechanic-timer/game.js

Let’s jump into the details, to look at the following groups of code. First add this code block anywhere in your playState.create function

  this.timeLimit = 5;
  this.timeText = game.add.text(10, 10, "0:00");
  this.timeText.fill = "#000000";
  this.timer = game.time.events.loop(1000, 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)

Now, add these functions to your game at the end of your code.

var tick = function () {
    this.timeLimit--;
    var minutes = Math.floor(this.timeLimit / 60);
    var seconds = this.timeLimit - (minutes * 60);
    var timeString = addZeros(minutes) + ":" + addZeros(seconds);
    this.timeText.text = timeString;
    if (this.timeLimit === 0) {
        restart;
    }
};

var addZeros = function (num) {
    if (num < 10) {
        num = "0" + num;
    }
    return num;
};

var outofTime = function () {
    var splatNoise = game.add.audio("splat");
    splatNoise.play();
    game.state.start("play");
}

Let’s look at what is in the tick() function and a following function to add Zeros to our timer. We can see here that every time tick is called every second it;

  • reduces our time limit by one second
  • 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 calls the restart function to restart game
  • the addZeros function just adds zeros to numbers when we need them so ten seconds is 00:10 and not 00:1