Phaser for Beginners

Increasing difficulty by adding a timer

What if you had a time limit to complete the game? Let’s increase the difficulty by giving you only a minute to solve the game. timeLeft variable will keep track of the remaining time we have.

Now we have to prevent the player from cheating. If you remove the focus from the page, the game will pause. This means timer won’t decrease, and this is cheating. We are going to prevent this by setting stage.disableVisibilityChange property to true. Let’s add it in the title screen.

Now in the same way we added scoreText variable to have the score text displayed, we add a new variable to show the remaining time.

And when we initialize the game, we set the time limit to 60, which means you’ll have to complete the game in a minute. There’s no need to explain you how to create the text which will show the remaining time:

Anyway, there’s a couple of lines I want to show you in detail:

This time anchor.set(0, 1) means the anchor point is on the bottom left angle. The second line I want you to see is the one handling the timer.

This time we aren’t dealing with a timer which only runs once, but with a loop.

time.events.loop(delay, callback, callbackContext) adds a looped event that will repeat forever or until it’s stopped. It will call callback function in the callbackContext context.

Let’s have a look at the callback function, called decreaseTime:

It decreases the timer, then updates the text showing the time left. Run the game:

Having a timer is nice, but quite useless if once the time is over nothing happens.

Download Source

File: adding-a-timer.zip


Next Tutorial →

Showing Game Over screen

← Previous Tutorial

Showing the score