FramesPerSecondCounter.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using Microsoft.Xna.Framework;
  3. namespace MonoGame.Extended
  4. {
  5. public class FramesPerSecondCounter : IUpdateable
  6. {
  7. private bool _enabled;
  8. private int _updateOrder;
  9. private static readonly TimeSpan _oneSecondTimeSpan = new TimeSpan(0, 0, 1);
  10. private int _framesCounter;
  11. private TimeSpan _timer = _oneSecondTimeSpan;
  12. /// <inheritdoc />
  13. public bool Enabled
  14. {
  15. get => _enabled;
  16. set
  17. {
  18. if (_enabled == value)
  19. {
  20. return;
  21. }
  22. _enabled = value;
  23. EnabledChanged?.Invoke(this, EventArgs.Empty);
  24. }
  25. }
  26. /// <inheritdoc />
  27. public int UpdateOrder
  28. {
  29. get => _updateOrder;
  30. set
  31. {
  32. if (_updateOrder == value)
  33. {
  34. return;
  35. }
  36. _updateOrder= value;
  37. EnabledChanged?.Invoke(this, EventArgs.Empty);
  38. }
  39. }
  40. /// <inheritdoc />
  41. public event EventHandler<EventArgs> EnabledChanged;
  42. /// <inheritdoc />
  43. public event EventHandler<EventArgs> UpdateOrderChanged;
  44. public FramesPerSecondCounter()
  45. {
  46. }
  47. public int FramesPerSecond { get; private set; }
  48. public void Update(GameTime gameTime)
  49. {
  50. _timer += gameTime.ElapsedGameTime;
  51. if (_timer <= _oneSecondTimeSpan)
  52. return;
  53. FramesPerSecond = _framesCounter;
  54. _framesCounter = 0;
  55. _timer -= _oneSecondTimeSpan;
  56. }
  57. public void Draw(GameTime gameTime)
  58. {
  59. _framesCounter++;
  60. }
  61. }
  62. }