Reputation: 185
I'm working on a game in Phaser 3.24.1 and would like to create a game clock. The clock should be set at 00:00, or zero minutes and zero seconds, and start when the game starts. I want the game to stop when the clock reaches 99:99, or exactly 1 hr 40 minutes. I can create a simple timer that starts from zero with the following code:
timedEvent = this.time.addEvent({ delay: 6000000, callback: this.onClockEvent, callbackScope: this, repeat: 1 });
text.setText('Game Clock: ' + timedEvent.getElapsedSeconds().toString().substr(0, 4));
This code will create a timer event and get the elapsed time in seconds. What I want is for the clock to display minutes and seconds. How would I go about doing this?
Upvotes: 1
Views: 1963
Reputation: 8571
If you have seconds, which getElapsedSeconds() provides, you'll just need to do a bit of math to get the number of minutes:
let elapsedTime = timedEvent.getElapsedSeconds();
let minutes = Math.floor(elapsedTime / (minutes * 60));
let seconds = Math.floor(time - minutes);
You can now pull the minutes and seconds, making sure that you add a '0'
if the seconds is less than 10.
However, if you run this you won't ever see a number greater than '59' after the colon, since you want to display minutes and seconds.
let elapsedTime = 72.99;
let minutes = Math.floor(elapsedTime / 60);
let seconds = Math.floor(elapsedTime - (minutes * 60));
document.getElementById('result').innerText = minutes + ':' + seconds;
<div id="result"></div>
So what you probably want is to just display the number of seconds:
let elapsedTime = 172.99;
// You could deal with adding zeros, or just add a number to the seconds, and then skip it when you pull it for display.
let displayTime = (10000 + elapsedTime).toString().substr(1, 4);
document.getElementById('result').innerText = displayTime.substr(0, 2) + ':' + displayTime.substr(2, 2);
<div id="result"></div>
Upvotes: 2