Framerate GameComponent to calculate the frame rate (XNA Framework)

Microsoft XNA can be used to develop computer games. This code snippet contains a so called GameComponent written in C#. The GameComponent is called Framerate and it simply calculates the frame rate of the game at each Update cycle.

public class Framerate : Microsoft.Xna.Framework.GameComponent
    {
        public float frames = 0f;
        public float deltaFPSTime = 0f;

        public Framerate(Game game)
            : base(game)
        {
            this.Game.IsFixedTimeStep = false;
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            float fps = 1 / elapsed;
            deltaFPSTime += elapsed;
            if (deltaFPSTime > 1)
            {
                this.FPS = fps;
                deltaFPSTime -= 1;
            }

            base.Update(gameTime);
        }

        public float FPS { get { return this.frames; } set { this.frames = value; } }
    }

The FPS property can be used to set or get the current frame rate.

This entry was posted in C# and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?