ChargeSwitch.cs 2.5 KB

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