15 October 2009

How To Create Flash Game Level Timer

In this post I'll explain how to create Flash game level timer mechanism. Code I'm using here is very simple, it's not something you should use in your final product. Code is ActionScript2.0. Sample FLA is Flash 8 file and it demonstrates how timer works.




Graphic elements are simple. We have startBtn movie clip in Library with 'startlevel' instance on Stage. Another graphic element is dynamic single-line text field with instance name 'timeleft'. When you start sample file situation our text field shows time left in minutes and seconds. Start level button is visible and waiting for click. When that happens button get zero alpha (should be moved from Stage) and countdown timer start to work.



Some formating is done, so numbers are displayed like they should, instead of 1:1 we have 1:01 etc. Timer resets when reach 0:00 and start level button is visible again, waiting for action. In real time situation, you can have different level durations for different levels. That means you should replace maxCount variable with Array of different intervals each represents duration of levels in seconds.

Here is the code:


var count:Number = 0;
var maxCount:Number = 75;
var intervalID:Number;
var timerStarted = false;
var temp:Number;

if(maxCount < 60) {
timeleft.text = "0 : "+maxCount;
} else {
if((maxCount%60)<10) {
timeleft.text = Math.floor((maxCount/60))+" : 0"+(maxCount%60);
} else {
timeleft.text = Math.floor((maxCount/60))+" : "+(maxCount%60);
}
}

startlevel.onRelease = function() {
if(!(timerStarted)) {
intervalID = setInterval(_root, "hronos", 1000);
timerStarted = true;
this._alpha = 0;
}
}

function hronos():Void {
if(count < maxCount) {
count++;
temp = maxCount - count;
if(temp < 60) {
if(temp < 10) {
timeleft.text = "0 : 0"+temp;
} else {
timeleft.text = "0 : "+temp;
}
} else {
if((temp%60)<10) {
timeleft.text = Math.floor((temp/60))+" : 0"+(temp%60);
} else {
timeleft.text = Math.floor((temp/60))+" : "+(temp%60);
}
}
} else {
clearInterval(intervalID);
timerStarted = false;
count = 0;
startlevel._alpha = 100;
}
}



*_*

1 comments:

Cris Monde said...

That's great! Thanks for sharing it to us. Now I know what codes they are using to make that level timer.

Cris | Flash Developer Philippines

 

template by blogger templates