Transition.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using Microsoft.Xna.Framework;
  3. namespace MonoGame.Extended.Screens.Transitions
  4. {
  5. public enum TransitionState { In, Out }
  6. public abstract class Transition : IDisposable
  7. {
  8. private readonly float _halfDuration;
  9. private float _currentSeconds;
  10. protected Transition(float duration)
  11. {
  12. Duration = duration;
  13. _halfDuration = Duration / 2f;
  14. }
  15. public abstract void Dispose();
  16. public TransitionState State { get; private set; } = TransitionState.Out;
  17. public float Duration { get; }
  18. public float Value => MathHelper.Clamp(_currentSeconds / _halfDuration, 0f, 1f);
  19. public event EventHandler StateChanged;
  20. public event EventHandler Completed;
  21. public void Update(GameTime gameTime)
  22. {
  23. var elapsedSeconds = gameTime.GetElapsedSeconds();
  24. switch (State)
  25. {
  26. case TransitionState.Out:
  27. _currentSeconds += elapsedSeconds;
  28. if (_currentSeconds >= _halfDuration)
  29. {
  30. State = TransitionState.In;
  31. StateChanged?.Invoke(this, EventArgs.Empty);
  32. }
  33. break;
  34. case TransitionState.In:
  35. _currentSeconds -= elapsedSeconds;
  36. if (_currentSeconds <= 0.0f)
  37. {
  38. Completed?.Invoke(this, EventArgs.Empty);
  39. }
  40. break;
  41. default:
  42. throw new ArgumentOutOfRangeException();
  43. }
  44. }
  45. public abstract void Draw(GameTime gameTime);
  46. }
  47. }