How to make a timer that displays the game's run time

I’ve been searching everywhere but I can’t seem to find a way to display how long my game has been running in seconds. In my game you have to last as long as possible so the higher the time, the higher your score/rank.

Right now, I have some styled text:
var initalTime = 0;
var timeTextStyle = {font: "24px Roboto", fill: '#E43AA4', stroke: '#000', strokeThickness: 4};

And I just want to display some text that shows the game time while the game is running and then stop running it when the game is over.

How do I do this in Phaser 3?

You can get the game’s time in a few ways:

  1. scene.time.now will give you the game’s time in milli seconds.
  2. The scene’s update method gives it to you as well
    update(time, delta)

You can then convert them to seconds by multiplying them with 0.001.

Try var seconds = scene.time.now * 0.001 or update(time, delta) {var seconds = time * 0.001 }

2 Likes

Ok So I used the update function’s time member and for some reason, the time seems to “stack up” when being displayed on screen. How can I fix this?

Also, how can I format the display of the time so that it just shows the whole number without decimals?

This is the code I am using to display the time:
var gameRuntime = time * 0.001;
var timeTextStyle = {font: "24px Roboto", fill: '#E43AA4', stroke: '#000', strokeThickness: 4};
timeText = this.add.text(16,16, gameRuntime, timeTextStyle);

So I figured it out on my own.

this.add.text() renders a new text onto the screen. If I want to update an existing text field, I have to use the setText() method instead.

Then, to round the number to a whole number and not display the trailing decimals, I simply use Math.round(time).

So as a complete solution, my code looks like:

var timeText;

function create(){
  var timeTextStyle = {font: "24px Roboto", fill: '#E43AA4', stroke: '#000', strokeThickness: 4}; 
  timeText = this.add.text(16,16, "Time Survived: ", timeTextStyle); //Elapsed Time Text
}

function update(time){
var gameRuntime = time * 0.001; //Converted to Seconds
    timeText.setText("Time Survived: " + Math.round(gameRuntime) + " seconds");
}
5 Likes

Ah thats’s nice, :metal: