FrameRateCalculator.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. namespace FirstGearGames.Utilities.Maths
  3. {
  4. public class FrameRateCalculator
  5. {
  6. #region Private.
  7. /// <summary>
  8. /// Time used to generate Frames.
  9. /// </summary>
  10. private float _timePassed = 0f;
  11. /// <summary>
  12. /// Frames performed in TimePassed. Float is used to reduce casting.
  13. /// </summary>
  14. private float _frames = 0;
  15. #endregion
  16. #region Const.
  17. /// <summary>
  18. /// How many frames to pass before slicing calculation values.
  19. /// </summary>
  20. private const int RESET_FRAME_COUNT = 60;
  21. /// <summary>
  22. /// Percentage to slice calculation values by. Higher percentages result in smoother frame rate adjustments.
  23. /// </summary>
  24. private const float CALCULATION_SLICE_PERCENT = 0.7f;
  25. #endregion
  26. /// <summary>
  27. /// Gets the current frame rate.
  28. /// </summary>
  29. /// <returns></returns>
  30. public int GetIntFrameRate()
  31. {
  32. return Mathf.CeilToInt((_frames / _timePassed));
  33. }
  34. /// <summary>
  35. /// Gets the current frame rate.
  36. /// </summary>
  37. /// <returns></returns>
  38. public float GetFloatFrameRate()
  39. {
  40. return (_frames / _timePassed);
  41. }
  42. /// <summary>
  43. /// Updates frame count and time passed.
  44. /// </summary>
  45. public bool Update(float unscaledDeltaTime)
  46. {
  47. _timePassed += unscaledDeltaTime;
  48. _frames++;
  49. if (_frames > RESET_FRAME_COUNT)
  50. {
  51. _frames *= CALCULATION_SLICE_PERCENT;
  52. _timePassed *= CALCULATION_SLICE_PERCENT;
  53. return true;
  54. }
  55. else
  56. {
  57. return false;
  58. }
  59. }
  60. }
  61. }