AS3:Main
This is a simple little gadget you can easily place in your games, to see what speed it is running at. This was an experiment for me, to try out AS3 and tone my OOP.
Previous reading:
Object Orientated Programming
Timer Object
Text Fields
Events
The FPS display is a custom class I created. So create a new .as file in the same directory as your flash that you wish to include it in, and name it "FPS".
You first need to import some packages that we will need:
package {
import flash.display.*;
import flash.text.*;
import flash.utils.*;
import flash.events.*;
The display will simply be used to draw the background for the display, the text for showing the FPS, utils for the timer, and events for, well, events.
Next we must start the class proper, and define some variables / objects:
public class FPS extends Sprite {
private var frameR:int = 0;
private var count:int = -1;
private var textBx:TextField = new TextField();
private var textFm:TextFormat = new TextFormat("Arial",12);
"frameR" will be the current FPS. "count" will count how many frames pass every second. "textBx" is the text field that will display the FPS. Finally, "textFm" will format the text field, so it isn't Times New Roman.
Following this is the constructor, that runs when a FPS object is created:
public function FPS (stage:Object, xx:int, yy:int):void {
var timer:Timer = new Timer(1000,0);
timer.addEventListener (TimerEvent.TIMER, addCount);
stage.addEventListener (Event.ENTER_FRAME , addFrame);
this.graphics.lineStyle (1,0,1);
this.graphics.beginFill (0xFFFFFF,1);
this.graphics.drawRect (xx,yy,48,16);
addChild(textBx);
textBx.x = xx;
textBx.y = yy;
textBx.width = 48;
textBx.height = 16;
timer.start();
}
The parameters are the Stage object, desired x and desired y position respectively. A timer object is created, with an interval of one second (1,000 milliseconds). A listener is added, that runs the function "addCount" every second. The stage object then has a listener added, that runs "addFrame" every time a frame passes. A box is drawn as a background for the FPS display, and the text field is moved into position. Finally, the timer object starts ticking.
Lastly, the functions referred to above need to be created:
private function addCount (TimerEvent):void {
frameR = count;
count = -1;
textBx.text = "FPS "+String(frameR);
textBx.setTextFormat(textFm);
}
private function addFrame (Event):void {
count++;
}
"addCount" resets the counter, and then displays the FPS in the text field. "addFrame" adds to the variable "count" every frame. Oh, and you might want to add two "}"'s at the end.
Well, that's it. This may not be the simplest way to do this, but I used the creation of this to teach myself more about AS3. Thanks for reading.