Browse Source

add FPS counter

GitOrigin-RevId: 7186a6f3cd
master
Colin McMillen 4 years ago
parent
commit
568bcf8071
  1. 26
      Jumpy.Shared/FPSCounter.cs
  2. 1
      Jumpy.Shared/Jumpy.Shared.projitems
  3. 9
      Jumpy.Shared/JumpyGame.cs

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

1
Jumpy.Shared/Jumpy.Shared.projitems

@ -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" />

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

Loading…
Cancel
Save