27
JUN

Flash AS3 Count Up Game Timer example

Although there are many countdown examples available on the web, I couldn’t find a decent count up timer for my game Aidan Junior. So I decided to create one myself and post it for you to view and download.

So, lets get started:

var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;

Firstly, we create a simple timer with a tick delay of 100 milliseconds.
We add an event listener to it and declare a variable that we’ll use later to store the elapsed time.

function timerTickHandler(Event:TimerEvent):void
{
    timerCount += 100;
    toTimeCode(timerCount);
}

This handler increments the timerCount with the elapsed 100 milliseconds and calls the toTimeCode function.
Almost there, now let’s take a look at the last step.

function toTimeCode(milliseconds:int) : void
{
    //creating a date object using the elapsed milliseconds
    var time:Date = new Date(milliseconds);

    //define minutes/seconds/mseconds
    var minutes:String = String(time.minutes);
    var seconds:String = String(time.seconds);
    var miliseconds:String = String(Math.round(time.milliseconds)/100);

    //add zero if neccecary, for example: 2:3.5 becomes 02:03.5
    minutes = (minutes.length != 2) ? '0'+minutes : minutes;
    seconds = (seconds.length != 2) ? '0'+seconds : seconds;

    //display elapsed time on in a textfield on stage
    timer_txt.text = minutes + ":" + seconds+"." + miliseconds;

}

And that’s it! I simply converted the elapsed time into minutes, seconds and milliseconds and displayed in on stage.

Feel feel to download and use the .fla file.

Result:

Download:
Download Fla