Saturday, January 1, 2011

XNA Game Development Tips and Tricks 4: Forcing and Calculating Frame Rates

Happy New Year 2011 to everyone.

We are going to see how we can control Frame Rates and how we can calculate current Frame rate at which game is getting rendered.

Frame rates are very very important part of game, actually speaking frame rats are important in every aspect of not just games but also in life.

Frame rates in video games means rate at which images are being rendered on the screen known as FPS (Frames Per Second). If you do not set correct FPS for game,  gamers will have weird experiences. For example lower Frames Per Second (FPS) will not give them illusion of motion and it will affect the user’s interaction with the game. Today games lock their frame rates to give a steady performance. If you have slower device game frame rates will drop and if you have very high end device game frame rates will increase and may give bad experience to players. Locking Frame Rates will make sure Frame Rates does not go beyond particular point, but we will not be able to control Low Frame Rates much because Low Frame Rates are very much dependent on the resources available.

Link will give you good examples at Frame Rate Samples : http://spng.se/frame-rate-test/

Windows Phone 7 forces 30 FPS, so whenever you create game for Windows Phone 7, you will see one line of code:

TargetElapsedTime = TimeSpan.FromTicks(333333);

if you increase Ticks from 333333 to 666666 you will notice decrease in Frame Rates, and if you decrease Ticks from 333333 to 111111 you will notice increase in Frame Rates. On Windows Phone 7 you will not get higher frame rates, because Windows Phone 7 OS forces 30 FPS, but on Console or PC you will see increase in Frames if your device is capable of doing so.

Now let us look at how we can calculate frames. Write following code in Class declaration.

float CumulativeFrameTime;
int NumFrames;
int FramesPerSecond;
SpriteFont msgFont;

Write following code in LoadContent method.

msgFont = Content.Load<SpriteFont>("score");

Write following code in Draw method.

CumulativeFrameTime += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 1000f;
NumFrames++;
if (CumulativeFrameTime >= 1f)
{
    FramesPerSecond = NumFrames;
    NumFrames = 0;
    CumulativeFrameTime -= 1f;
}
spriteBatch.DrawString(msgFont, "FPS: " + FramesPerSecond.ToString(), new Vector2(0, 0), Color.Black);

Above code will calculate FPS and display it on the screen, it is very useful when you are developing game to see, at what point of time your game is dropping FPS and how you can improve on that and many other things.

No comments:

Post a Comment