Slide.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.Diagnostics;
  3. namespace OpenVIII
  4. {
  5. public class Slide<T>
  6. {
  7. #region Constructors
  8. public Slide(T start, T end, TimeSpan totalTime, Func<T, T, float, T> function)
  9. {
  10. Start = start;
  11. End = end;
  12. TotalTime = totalTime;
  13. //Debug.Assert(TotalTime != TimeSpan.Zero);
  14. Function = function;
  15. }
  16. #endregion Constructors
  17. #region Properties
  18. public T Current { get; private set; }
  19. public TimeSpan CurrentTime { get; private set; }
  20. public float CurrentPercent { get; private set; }
  21. public bool Repeat { get; set; } = false;
  22. /// <summary>
  23. /// When started wait this many MS before moving.
  24. /// </summary>
  25. public TimeSpan Delay { get; set; }
  26. public bool Done => CurrentTime - Delay >= TotalTime;
  27. public T End { get; set; }
  28. public Func<T, T, float, T> Function { get; set; }
  29. public bool Reversed { get; private set; } = false;
  30. public TimeSpan ReversedTime { get; set; }
  31. public T Start { get; set; }
  32. public virtual TimeSpan TotalTime { get; set; }
  33. #endregion Properties
  34. #region Methods
  35. public void Restart() => CurrentTime = TimeSpan.Zero;
  36. public void Reverse()
  37. {
  38. var tempValue = Start;
  39. Start = End;
  40. End = tempValue;
  41. if (ReversedTime > TimeSpan.Zero)
  42. {
  43. var tempTime = ReversedTime;
  44. ReversedTime = TotalTime;
  45. TotalTime = tempTime;
  46. }
  47. Reversed = !Reversed;
  48. }
  49. public void ReverseRestart()
  50. {
  51. Reverse();
  52. Restart();
  53. }
  54. public T Update()
  55. {
  56. if ((!Done || Repeat) && Function != null)
  57. {
  58. UpdatePercent();
  59. Current = Function(Start, End, CurrentPercent);
  60. return Current;
  61. }
  62. return End;
  63. }
  64. public float UpdatePercent()
  65. {
  66. CurrentPercent = 1f;
  67. if (!Done || Repeat)
  68. {
  69. CurrentTime += Memory.ElapsedGameTime;
  70. //CheckRepeat();
  71. //return CurrentPercent = CurrentTime < Delay ? 0f : (float)(Done ? 1f : (CurrentTime - Delay).TotalMilliseconds / TotalTime.TotalMilliseconds);
  72. CheckRepeat();
  73. if (CurrentTime < Delay)
  74. return CurrentPercent = 0f;
  75. return CurrentPercent = (float)((CurrentTime - Delay).Ticks / (double)TotalTime.Ticks);
  76. }
  77. else
  78. return CurrentPercent;
  79. }
  80. protected virtual void CheckRepeat()
  81. {
  82. if (Repeat && Done)
  83. CurrentTime = TimeSpan.FromTicks((CurrentTime - Delay).Ticks % TotalTime.Ticks);
  84. }
  85. public virtual void GotoEnd()
  86. {
  87. Current = End;
  88. CurrentTime = TotalTime;
  89. }
  90. #endregion Methods
  91. }
  92. }