ChargeSwitch.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //-----------------------------------------------------------------------------
  2. // ChargeSwitch.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Input;
  10. namespace InputReporter
  11. {
  12. /// <summary>
  13. /// A GamePad-controlled switch that fires after the switch "charges up"
  14. /// (typically by holding a button down) for a set duration.
  15. /// </summary>
  16. /// <remarks>
  17. /// Since all buttons are relevant for data viewing, we don't want to directly
  18. /// tie any button press to an action, like exiting the application. Our solution
  19. /// is to provide "charging" switches that run an event, like exiting, after holding
  20. /// the button down for a specified amount of time.
  21. /// </remarks>
  22. abstract class ChargeSwitch
  23. {
  24. public delegate void FireDelegate();
  25. public event FireDelegate Fire;
  26. private float duration = 3f;
  27. private float remaining = 0f;
  28. private bool active = false;
  29. public bool Active
  30. {
  31. get { return active; }
  32. }
  33. public ChargeSwitch(float duration)
  34. {
  35. Reset(duration);
  36. }
  37. public void Update(GameTime gameTime, ref GamePadState gamePadState)
  38. {
  39. active = IsCharging(ref gamePadState);
  40. if (active)
  41. {
  42. if (remaining > 0f)
  43. {
  44. remaining -= (float)gameTime.ElapsedGameTime.TotalSeconds;
  45. if (remaining <= 0f)
  46. {
  47. if (Fire != null)
  48. {
  49. Fire();
  50. }
  51. }
  52. }
  53. }
  54. else
  55. {
  56. // reset to the current duration
  57. Reset(duration);
  58. }
  59. }
  60. public void Reset(float duration)
  61. {
  62. if (duration < 0f)
  63. {
  64. throw new ArgumentOutOfRangeException("duration");
  65. }
  66. this.remaining = this.duration = duration;
  67. }
  68. protected abstract bool IsCharging(ref GamePadState gamePadState);
  69. }
  70. }