Game Development Reference
In-Depth Information
Now the only thing you still need to do is implement the update method to program the timer
behavior. As a first step, you only update the timer if it's running. So if the timer isn't running, you
return from the method:
if (!this.running)
return;
Then, as usual you subtract the elapsed game time from the current remaining time:
this._timeLeft -= delta;
Next you create the text that you want to print on the screen. You could simply print the number of
seconds on the screen, but let's make the timer a bit more generic so it's also possible to define a
timer that can handle minutes as well as seconds. For example, if you want to define a timer that
counts down from two minutes, you initialize it as follows:
this._timeLeft = 120;
You want to display “2:00” instead of “120” on the screen. To do this, you need to calculate in the
update method how many minutes are left. You use the Math.floor method for this:
var minutes = Math.floor(this._timeLeft / 60);
Using this approach, you make sure the number of minutes is never higher than allowed. For example,
Math.floor(119) gives you 1 as a result, which is exactly what you need, because 119 seconds
remaining translates to 1 minute and 119 - 60 = 59 seconds remaining.
By calculating the remainder after dividing _timeLeft by 60, you get the number of seconds. In order
to only have integer numbers, you need to round the number of seconds as well, but you use the
Math.ceil method for this. This method always rounds up: for example, Math.ceil(1.2) has a result
of 2. You always want to round up because you need to make sure you display zero seconds only
when there really is no time left. Here is how you calculate the number of seconds:
var seconds = Math.ceil(this._timeLeft % 60);
Because you don't want to display negative times, you add the following if instruction:
if (this._timeLeft < 0)
minutes = seconds = 0;
Note that you use operator chaining here to set the minutes and seconds. The following if
instruction does exactly the same:
if (this._timeLeft < 0) {
minutes 0;
seconds = 0;
}
 
Search WWH ::




Custom Search