Pages

Sunday, October 25, 2020

Frames Per Second Counter

So, I'm going to try something new. I'm not happy with the way it is rendering 100% but it should copy/paste fine. Most probably have one by now but I thought I'd share my frames per second component outside of a tutorial on its own. It renders the FPS into the title bar of the window and the output log in Visual Studio. I recommend using the base constructor and adding it to the list of game components in the constructor using Components.Add(new FramesPerSecond(this)).

UPDATE: I fixed the issues I had with code.


using System;
using Microsoft.Xna.Framework;

namespace Psilibrary
{
    public sealed class FramesPerSecond : DrawableGameComponent
    {
        private float _fps;
        private float _updateInterval = 1.0f;
        private float _timeSinceLastUpdate = 0.0f;
        private float _frameCount = 0;

        public FramesPerSecond(Game game)
            : this(game, false, false, game.TargetElapsedTime)
        {
        }

        public FramesPerSecond(
            Game game, 
            bool synchWithVerticalRetrace, 
            bool isFixedTimeStep, 
            TimeSpan targetElapsedTime)
            : base(game)
        {
            GraphicsDeviceManager graphics = 
                (GraphicsDeviceManager)Game.Services.GetService(
                    typeof(IGraphicsDeviceManager));

            graphics.SynchronizeWithVerticalRetrace = synchWithVerticalRetrace;
            Game.IsFixedTimeStep = isFixedTimeStep;
            Game.TargetElapsedTime = targetElapsedTime;
        }

        public sealed override void Draw(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            _frameCount++;
            _timeSinceLastUpdate += elapsed;

            if (_timeSinceLastUpdate > _updateInterval)
            {
                _fps = _frameCount / _timeSinceLastUpdate;
                System.Diagnostics.Debug.WriteLine("FPS: " + _fps.ToString());
                Game.Window.Title = "FPS: " + ((int)_fps).ToString();
                _frameCount = 0;
                _timeSinceLastUpdate -= _updateInterval;
            }

            base.Draw(gameTime);
        }
    }
}

No comments:

Post a Comment