From 568bcf80716c7e0385afd41ea6c2fcb2c8c164f7 Mon Sep 17 00:00:00 2001 From: Colin McMillen Date: Sun, 8 Dec 2019 21:19:50 -0500 Subject: [PATCH] add FPS counter GitOrigin-RevId: 7186a6f3cd9ba35ff51b2232ebef67cbe3ad544c --- Jumpy.Shared/FPSCounter.cs | 26 ++++++++++++++++++++++++++ Jumpy.Shared/Jumpy.Shared.projitems | 1 + Jumpy.Shared/JumpyGame.cs | 9 ++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 Jumpy.Shared/FPSCounter.cs diff --git a/Jumpy.Shared/FPSCounter.cs b/Jumpy.Shared/FPSCounter.cs new file mode 100644 index 0000000..0c9c98b --- /dev/null +++ b/Jumpy.Shared/FPSCounter.cs @@ -0,0 +1,26 @@ +using System; + +namespace Jumpy { + class FpsCounter { + private double fps = 0; + private int[] frameTimes = new int[60]; + private int idx = 0; + + public double Fps { + get => fps; + } + + public void Update() { + var now = Environment.TickCount; // ms + if (frameTimes[idx] != 0) { + var timeElapsed = now - frameTimes[idx]; + fps = 1000.0 * frameTimes.Length / timeElapsed; + } + frameTimes[idx] = now; + idx++; + if (idx == frameTimes.Length) { + idx = 0; + } + } + } +} diff --git a/Jumpy.Shared/Jumpy.Shared.projitems b/Jumpy.Shared/Jumpy.Shared.projitems index e3ac01f..6a595ce 100644 --- a/Jumpy.Shared/Jumpy.Shared.projitems +++ b/Jumpy.Shared/Jumpy.Shared.projitems @@ -10,6 +10,7 @@ + diff --git a/Jumpy.Shared/JumpyGame.cs b/Jumpy.Shared/JumpyGame.cs index 6e8a01a..107020e 100644 --- a/Jumpy.Shared/JumpyGame.cs +++ b/Jumpy.Shared/JumpyGame.cs @@ -2,6 +2,7 @@ using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; +using System; using System.Collections.Generic; namespace Jumpy { @@ -14,6 +15,7 @@ namespace Jumpy { bool fullScreen = false; IDisplay display; + FpsCounter fpsCounter = new FpsCounter(); Player player; public JumpyGame() { @@ -70,6 +72,10 @@ namespace Jumpy { // Called when the game should draw itself. protected override void Draw(GameTime gameTime) { + // We need to update the FPS counter in Draw() since Update() might get called more + // frequently, especially when gameTime.IsRunningSlowly. + fpsCounter.Update(); + // Draw scene to RenderTarget. GraphicsDevice.SetRenderTarget(renderTarget); // GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true }; @@ -87,7 +93,8 @@ namespace Jumpy { Rectangle drawRect = new Rectangle( 0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); spriteBatch.Draw(renderTarget, drawRect, Color.White); - spriteBatch.DrawString(font, "FPS: 60", new Vector2(10, 10), Color.White); + string fpsText = $"FPS: {fpsCounter.Fps:F1}"; + spriteBatch.DrawString(font, fpsText, new Vector2(10, 10), Color.White); spriteBatch.End(); base.Draw(gameTime);