Talking about Actionscript 3 and Flash.
A lot of time ago I wrote about AS2 time management in Flash simple timer/countdown. Now it’s time to see how to manage time with AS3.
AS3 has its own class to manage time, the Timer
class. You can read some documentation about this class in the official AS3 page, but in this test drive I am going to create two different timers… one using time intervals and one checking for elapsed time at every frame.
You will find some differences.
package {
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.Timer;
import flash.utils.getTimer;
import flash.events.TimerEvent;
import flash.text.TextField;
public class as3timer extends Sprite {
var interval_timer = new timetext;
var frame_timer = new timetext;
public function as3timer() {
addChild(interval_timer);
addChild(frame_timer);
frame_timer.y = 50;
var time_count:Timer = new Timer(1000);
time_count.addEventListener(TimerEvent.TIMER, show_time);
stage.addEventListener(Event.ENTER_FRAME,on_enter_frame);
time_count.start();
}
function show_time(event:TimerEvent) {
interval_timer.txt.text = event.target.currentCount;
}
function on_enter_frame(event:Event) {
var elapsed = getTimer();
frame_timer.txt.text = Math.floor(elapsed/1000)+"."+(elapsed%1000);
}
}
}
Let’s analyze this script:
Line 4: I need Timer
class to create a Timer
variable.
Line 5: I need getTimer
class to use getTimer
function. getTimer
returns the number of milliseconds since the movie started.
Line 6: I need TimerEvent
class to make a time event listener.
Lines 9-10: interval_timer
and frame_timer
are two dynamic text fields that will contain the number of seconds elapsed with both methods. Since I am using dynamic text fields, I had to include the TextField class at line 7.
Line 15: This is the core of the time based method. When I use new Timer(x, y);
, I dispatch an event every x
milliseconds for y
times. If y
is omitted, I dispatch an event every x
milliseconds forever. In this case, I am dispatching the event every second, forever.
Line 16: This is the listener for the timer event that points to the show_time
function.
Line 17: This is a simple listener for a new frame pointing on on_enter_frame
function
Line 18: Starting the timer
Line 21: Updating the dynamic text field with currentCount
, that stores the number of times the target has been triggered (in this case the number of seconds).
Line 25: In this case I simply get the time passed with getTimer
and display it on screen.
Here it is:
At a first glance both methods work, but if you let them run for a while, you will notice they will differ more and more.
Look at this picture:
If you let timers run a lot, the difference is quite big.
What kind of timer would you use?
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.