Tuesday, July 20, 2010

Dynamically setting and showing FPS in AS3

In this tutorial we will learn how to set frame rate of our movie with AS3 during its playback and how to create a simple fps displayer.

Stage has a new property frameRate, that can be dynamically changed from any frame:

stage.frameRate=18;

It can contain any value between 0.01 and 1000, but remember that the best FPS for any movie would be in the 24 - 32 range. Human eye (unless its trained) can't see more than 24 frames per second.

However, frameRate will only show you what the FPS is meant to be. If you want to find out which 'speed' is your flash running at, use the following method:

var showfps:TextField = new TextField;
addChild(showfps);
var fps:int
var time:int
var prevtime:int = 0

stage.addEventListener(Event.ENTER_FRAME, loop);

function loop(Event){
 time=getTimer();
 fps=1000 / (time - prevtime);
 showfps.text="FPS " + fps;
 prevtime=getTimer();
 }

What we do is create 2 variables - time and prevtime, that change every frame. The getTimer function shows us how many milliseconds have elapsed, so we tell our 'time' variable to take this value every frame and compare it to milliseconds elapsed a frame before. We deduct prevtime from time, and then we divide 1000 by this value (to show how many seconds (not milliseconds) have passed per frame).

That's how you do it!

1 comment:

Muhammad Farooqi said...

Thank you boy.. i like it..

Post a Comment