Today while working on an app that I’ll probably be posting up here in the next few days I had need for an actual frame rate counter of which Flash doesn’t seem to provide for us. It was a simple enough task though so I figured no big deal, I’ll just write one myself. It wouldn’t be the first time I’ve done such a thing, just the first time in Actionscript. Then, I decided why not share it with the world! So, here it is with a short explanation in case anyone doesn’t understand how frame rate is calculated.
The class only has a few variables and they are:
- targetRate: The framerate you want to be running at (not really implemented for any purpose)
- currentRate: The framerate the app is currently running at
- framesPassed: Frames passed in the last second (to calculate the currentRate)
- secondTimer: A timer that goes off every second
The constructor requires no arguments and simply sets up the secondTimer. It looks like this:
public function FPS():void
{
//create timer
this.secondTimer = new Timer(1000);
this.secondTimer.start();
//listeners
this.secondTimer.addEventListener(TimerEvent.TIMER, handleTimer);
this.addEventListener(Event.ENTER_FRAME, update);
}
The next function is the ‘update’ function called every frame and all it does is increment ‘framesPassed’ to keep count of the number of frames. No need to post it, it’s a one liner.
Whenever the timer goes off ‘handleTimer’ is called which simply stores the ‘framesPassed’ variable as the currentRate and resets framesPassed to 0. Since framesPassed was being incremented everytime a frame was entered and handleTimer is called once a second then it’s pretty simple logic to see that framesPassed will have the number of frames that happened in the last second, aka the current framerate of the app.
Lastly, there are some simple get functions in the class to return these values.
Now, if you don’t want to be throwing so many events with this class because it should really be a background class (although updating it once a second isn’t a big deal) you could always make the timer go off less frequently then just divide framesPassed/[duration of timer] to get your frame rate. But, it seems to work well as is.
Here’s a link to it, it’s yours to enjoy, just make reference to awesomeghost if you do!
