I made an update to my FPS counter. It is great to know the current FPS but the average FPS is also of great value. It gives you a better sense of how your game will perform over time. I also included a reset in case I need to test different areas of the game I'm working on. I thought I'd share the updates.
public class FramesPerSecond : DrawableGameComponent
{
private float _fps;
private float _updateInterval = 1.0f;
private float _timeSinceLastUpdate = 0.0f;
private float _frameCount = 0;
private float _totalSeconds;
private float _afps;
private float _totalFrames;
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 Initialize()
{
base.Initialize();
}
public sealed override void Update(GameTime gameTime)
{
KeyboardState ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.F1))
{
_fps = 0;
_afps = 0;
_timeSinceLastUpdate = 0;
_totalFrames = 0;
_frameCount = 0;
_totalSeconds = 0;
}
base.Update(gameTime);
}
public sealed override void Draw(GameTime gameTime)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
_frameCount++;
_timeSinceLastUpdate += elapsed;
_totalFrames++;
if (_timeSinceLastUpdate > _updateInterval)
{
_totalSeconds++;
_fps = _frameCount / _timeSinceLastUpdate;
_afps = _totalFrames / _totalSeconds;
System.Diagnostics.Debug.WriteLine("FPS: " + _fps.ToString());
#if !ANDROID
Game.Window.Title = "FPS: " + _fps.ToString();
#endif
_frameCount = 0;
_timeSinceLastUpdate -= _updateInterval;
System.Diagnostics.Debug.WriteLine("AFPS: " + _afps.ToString());
#if !ANDROID
Game.Window.Title += " - AFPS: " + _afps.ToString();
#endif
}
base.Draw(gameTime);
}
}
No comments:
Post a Comment