add FPS counter

GitOrigin-RevId: 7186a6f3cd9ba35ff51b2232ebef67cbe3ad544c
This commit is contained in:
Colin McMillen 2019-12-08 21:19:50 -05:00
parent c247b6c389
commit 568bcf8071
3 changed files with 35 additions and 1 deletions

View File

@ -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;
}
}
}
}

View File

@ -10,6 +10,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Camera.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FpsCounter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IDisplay.cs" />
<Compile Include="$(MSBuildThisFileDirectory)KeyboardInput.cs" />
<Compile Include="$(MSBuildThisFileDirectory)JumpyGame.cs" />

View File

@ -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);