@willmotil wrote:
I was organizing my examples and thought i would post this for anyone who just wants a quick fps counter or to see how to do it.
Here is the game1 example of the class being used.
Its very simple to use 3 lines of code;using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace SimpleFpsCounter { public class Game1 : Game { private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; SpriteFont font; KeyboardState previousState; // Add the class SimpleFps fps = new SimpleFps(); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { this.TargetElapsedTime = TimeSpan.FromSeconds(1d / 60d); this.IsFixedTimeStep = false; graphics.SynchronizeWithVerticalRetrace = false; graphics.ApplyChanges(); base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("PipeLineToolCreatedFont"); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { KeyboardState state = Keyboard.GetState(); if (state.IsKeyDown(Keys.Escape)) Exit(); // Update the fps fps.Update(gameTime); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Moccasin); spriteBatch.Begin(); // Draw the fps msg fps.DrawFps(spriteBatch, font, new Vector2(10f, 10f), Color.MonoGameOrange); spriteBatch.End(); base.Draw(gameTime); } } }
Here is the class.
You can just add the class below the game1 class to test it.using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SimpleFpsCounter { public class SimpleFps { private double frames = 0; private double updates = 0; private double elapsed = 0; private double last = 0; private double now = 0; public double msgFrequency = 1.0f; public string msg = ""; /// <summary> /// The msgFrequency here is the reporting time to update the message. /// </summary> public void Update(GameTime gameTime) { now = gameTime.TotalGameTime.TotalSeconds; elapsed = (double)(now - last); if (elapsed > msgFrequency) { msg = " Fps: " + (frames / elapsed).ToString() + "\n Elapsed time: " + elapsed.ToString() + "\n Updates: " + updates.ToString() + "\n Frames: " + frames.ToString(); //Console.WriteLine(msg); elapsed = 0; frames = 0; updates = 0; last = now; } updates++; } public void DrawFps(SpriteBatch spriteBatch, SpriteFont font, Vector2 fpsDisplayPosition, Color fpsTextColor) { spriteBatch.DrawString(font, msg, fpsDisplayPosition, fpsTextColor); frames++; } } }
Posts: 1
Participants: 1