mort8088 Just another WordPress site


XNA – FPS Drawable Game Component

Originally posted 2007 - Updated for XNA 4.0

A quick and useful component that displays the number of calls to the Draw method in your game.

In Visual Studio create a new "Windows Game(4.0)" project or load your current project, I'll work with a new project called Tut001.

Right click on your XNA Game project and select "Add/New Item"

From the "Add New Item" dialog select "GameComponent" and call it dgcFPS.cs

You'll have the code below, I've just stripped out the comments to tidy it up:-

Change the


And add the following methods:-

Next add the following private variables:-

Next Add a property for ShowFPS:-

Now fill out the methods we've already added:- Lets start with LoadContent, all we need here is to create a spritebatch for use in our draw method and the font that we are going to use I'm using a variable so we can change it at runtime.

The Update method is where we are going to do the math bit, keep track of the time taken and increment the TotalFrames by one then once a second has passed set the _Fps to TotalFrames and reset the ElapsedTime and TotalFrames ready for the next second.

Check that the Game wants to show the fps and call draw string to display it, Job done.

Now we'll add the constructor's I'm using multiple constructors to give me some flexibility in how I can use this component. To add a constructor to a class go the the line after the blank one that is added by default and type the following ctor then press tab twice hay presto another blank constructor just add args 🙂

First up the blank constructor, the default isn't blank as such because it takes Game as it's parameter but it doesn't do anything and relies on the default values we set when we declared the variables.

Next up, are we showing by default? when I was testing this component it took me a few minuets to spot that it wasn't showing the FPS count because I had defaulted _ShowFPS to false so I added this one. I have added a parameter of type bool that sets the show property.

Now if you want a different font at start up rather than recompile the component, because you might not be able to, there's this one by passing the string to a SpriteFont file that you know will be with your Game you can set it here to avoid a run time error.

Now all that remains is to add the component to your Game add this code to you're Game1 constructor...

Comments (0) Trackbacks (0)

Sorry, the comment form is closed at this time.

Trackbacks are disabled.