Clock.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. namespace XGame.Framework.Time
  3. {
  4. public class Clock : IClock
  5. {
  6. private AlarmRepository _clientAlarmRepo;
  7. private AlarmRepository _serverAlarmRepo;
  8. private TimerRepository _timerRepo;
  9. public Clock(long timeStamp)
  10. {
  11. var realTime = UnityEngine.Time.realtimeSinceStartup;
  12. _clientAlarmRepo = new AlarmRepository()
  13. {
  14. time = new TimeStamp()
  15. {
  16. realtimeSinceStartup = realTime,
  17. timeStamp = timeStamp
  18. }
  19. };
  20. _serverAlarmRepo = new AlarmRepository()
  21. {
  22. time = new TimeStamp()
  23. {
  24. realtimeSinceStartup = realTime,
  25. timeStamp = timeStamp
  26. }
  27. };
  28. _timerRepo = new TimerRepository();
  29. }
  30. private AlarmRepository GetAlarmRepository(ClockType clockTyp = ClockType.Server)
  31. {
  32. return clockTyp == ClockType.Server ? _serverAlarmRepo : _clientAlarmRepo;
  33. }
  34. public void SetTime(long timestamp, ClockType clockTyp = ClockType.Server)
  35. {
  36. GetAlarmRepository(clockTyp).SetTime(timestamp);
  37. }
  38. public long GetNowTime(ClockType clockTyp = ClockType.Server)
  39. {
  40. var alarmTime = GetAlarmRepository(clockTyp).time;
  41. return alarmTime.timeStamp + (long)((UnityEngine.Time.realtimeSinceStartup - alarmTime.realtimeSinceStartup) * 1000);
  42. }
  43. public IAlarm AddAlarm(long triggerTimestamp, Action action, ClockType clockTyp = ClockType.Server)
  44. {
  45. return GetAlarmRepository(clockTyp).AddAlarm(action, GetNowTime(clockTyp), triggerTimestamp);
  46. }
  47. public ITimer AddDelayTimer(int delay, Action action)
  48. {
  49. return _timerRepo.AddDelayTimer(delay, action);
  50. }
  51. public ITimer AddLooperTimer(int delay, int interval, Action<int> action, int loopTime = -1)
  52. {
  53. return _timerRepo.AddLooperTimer(delay, interval, action, loopTime);
  54. }
  55. public void Update(int millisecond)
  56. {
  57. _clientAlarmRepo.ClockUpdate(millisecond);
  58. _serverAlarmRepo.ClockUpdate(millisecond);
  59. _timerRepo.ClockUpdate(millisecond);
  60. }
  61. public void Dispose()
  62. {
  63. _clientAlarmRepo.Dispose();
  64. _serverAlarmRepo.Dispose();
  65. _timerRepo.Dispose();
  66. }
  67. }
  68. }