Chapter 9 - FrameTimeManager.swf
The complete example is available in the Downloads Center. The ActionScript code for this example is:
In this example, a general-purpose FrameTimeManager class is used to calculate elapsed frame time for time-based calculations. The FrameTimeManager class makes use of a general-purpose Timer class. The SWF displays the elapsed frame time, which should be 1/30th of a second or .03333 seconds. The frame time will fluctuate, especially if other applications are running.
Main Timeline code:
import ch09.FrameTimeManager;
var frameTimeTextField:TextField;
this.createTextField("frame_time_textfield", 10, 0, 0, 550, 100);
frameTimeTextField = this["frame_time_textfield"];
var frameTimeTextFormat:TextFormat = new TextFormat();
frameTimeTextFormat.color = 0xFF0000;
frameTimeTextFormat.bold = true;
frameTimeTextFormat.size = 72;
frameTimeTextFormat.align = "center";
onEnterFrame = function () {
FrameTimeManager.calculateFrameTime();
frameTimeTextField.text = String(FrameTimeManager.getFrameSeconds());
frameTimeTextField.setTextFormat(frameTimeTextFormat);
}
ActionScript 2 class code - FrameTimeManager:
import ch09.Timer;
class ch09.FrameTimeManager {
static var frameTimeMilliseconds:Number;
static var frameTimeTimer:Timer = new Timer();
public static function calculateFrameTime():Void {
frameTimeMilliseconds = frameTimeTimer.milliseconds();
frameTimeTimer.restartTimer();
}
public static function getFrameSeconds():Number {
return frameTimeMilliseconds / 1000;
}
}
ActionScript 2 class code - Timer:
class ch09.Timer {
var startTime:Number = 0;
public function Timer () {
startTime = getTimer();
}
public function restartTimer():Void {
startTime = getTimer();
}
public function milliseconds():Number {
return (getTimer() - startTime);
}
public function seconds():Number {
return getSeconds();
}
private function getSeconds():Number {
return ( Math.floor( (getTimer() - startTime)/1000 ) );
}
public function minutes():Number {
return Math.floor(getSeconds() / 60);
}
public function remaining(time_allowed:Number):Number {
return time_allowed - milliseconds();
}
public function expire():Void {
startTime = -100000;
}
public function display():String {
var mins, secs;
mins = "00" + minutes();
mins = mins.substr(mins.length - 2, 2);
secs = "00" + seconds();
secs = secs.substr(secs.length - 2, 2);
return mins + ":" + secs;
}
public function displayRemaining(time_allowed:Number):String {
var mins, secs;
var millisRemaining = time_allowed - milliseconds();
var secsRemaining = Math.floor(millisRemaining / 1000);
var minsRemaining = Math.floor(secsRemaining / 60);
if (millisRemaining >=0) {
mins = "00" + minsRemaining;
mins = mins.substr(mins.length - 2, 2);
secs = "00" + secsRemaining;
secs = secs.substr(secs.length - 2, 2);
} else {
mins = "00";
secs = "00";
}
return mins + ":" + secs;
}
}

