TimeHelper.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. /// <summary>
  6. /// 时间管理器
  7. /// </summary>
  8. public class TimeHelper
  9. {
  10. /// <summary>
  11. /// 初始时间
  12. /// </summary>
  13. private DateTime mInitTime = DateTime.MaxValue;
  14. /// <summary>
  15. /// 倍数
  16. /// </summary>
  17. private float mSpeed = 1;
  18. /// <summary>
  19. /// 总持续毫秒数
  20. /// </summary>
  21. private double totalMillsec = 0;
  22. /// <summary>
  23. /// 上一次检查时间
  24. /// </summary>
  25. private DateTime mLastCheckTime = DateTime.MinValue;
  26. /// <summary>
  27. /// 是否暂停
  28. /// </summary>
  29. private bool mIsPause = false;
  30. /// <summary>
  31. /// 开始计时
  32. /// </summary>
  33. public void Start()
  34. {
  35. this.mInitTime = DateTime.MinValue;
  36. this.mSpeed = 1.0f;
  37. this.totalMillsec = 0;
  38. this.mLastCheckTime = DateTime.Now;
  39. this.mIsPause = false;
  40. }
  41. /// <summary>
  42. /// 获取当前时间倍率
  43. /// </summary>
  44. /// <returns>倍率值</returns>
  45. public float GetSpeed()
  46. {
  47. return this.mSpeed;
  48. }
  49. /// <summary>
  50. /// 设置时间倍率
  51. /// </summary>
  52. /// <param name="val">倍率值</param>
  53. public void SetSpeed(float val)
  54. {
  55. this.mSpeed = val;
  56. }
  57. /// <summary>
  58. /// 暂停计时器
  59. /// </summary>
  60. public void Pause()
  61. {
  62. this.Update();
  63. this.mIsPause = true;
  64. }
  65. /// <summary>
  66. /// 继续计时器
  67. /// </summary>
  68. public void Continue()
  69. {
  70. this.mIsPause = false;
  71. this.mLastCheckTime = DateTime.Now;
  72. }
  73. /// <summary>
  74. /// 时间刷新
  75. /// </summary>
  76. public void Update()
  77. {
  78. if (this.mIsPause == true)
  79. {
  80. return;
  81. }
  82. TimeSpan span = DateTime.Now - this.mLastCheckTime;
  83. this.totalMillsec += span.TotalMilliseconds * this.mSpeed;
  84. this.mLastCheckTime = DateTime.Now;
  85. }
  86. /// <summary>
  87. /// 获取当前时间
  88. /// </summary>
  89. /// <returns>时间</returns>
  90. public long Now()
  91. {
  92. return (long)this.totalMillsec;
  93. }
  94. }