Direction.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // Direction.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 System.Linq;
  12. using Microsoft.Xna.Framework.Input;
  13. #endregion
  14. namespace InputSequenceSample
  15. {
  16. /// <summary>
  17. /// Helper class for working with the 8-way directions stored in a Buttons enum.
  18. /// </summary>
  19. static class Direction
  20. {
  21. // Helper bit masks for directions defined with the Buttons flags enum.
  22. public const Buttons None = 0;
  23. public const Buttons Up = Buttons.DPadUp | Buttons.LeftThumbstickUp;
  24. public const Buttons Down = Buttons.DPadDown | Buttons.LeftThumbstickDown;
  25. public const Buttons Left = Buttons.DPadLeft | Buttons.LeftThumbstickLeft;
  26. public const Buttons Right = Buttons.DPadRight | Buttons.LeftThumbstickRight;
  27. public const Buttons UpLeft = Up | Left;
  28. public const Buttons UpRight = Up | Right;
  29. public const Buttons DownLeft = Down | Left;
  30. public const Buttons DownRight = Down | Right;
  31. public const Buttons Any = Up | Down | Left | Right;
  32. /// <summary>
  33. /// Gets the current direction from a game pad and keyboard.
  34. /// </summary>
  35. public static Buttons FromInput(GamePadState gamePad, KeyboardState keyboard)
  36. {
  37. Buttons direction = None;
  38. // Get vertical direction.
  39. if (gamePad.IsButtonDown(Buttons.DPadUp) ||
  40. gamePad.IsButtonDown(Buttons.LeftThumbstickUp) ||
  41. keyboard.IsKeyDown(Keys.Up))
  42. {
  43. direction |= Up;
  44. }
  45. else if (gamePad.IsButtonDown(Buttons.DPadDown) ||
  46. gamePad.IsButtonDown(Buttons.LeftThumbstickDown) ||
  47. keyboard.IsKeyDown(Keys.Down))
  48. {
  49. direction |= Down;
  50. }
  51. // Comebine with horizontal direction.
  52. if (gamePad.IsButtonDown(Buttons.DPadLeft) ||
  53. gamePad.IsButtonDown(Buttons.LeftThumbstickLeft) ||
  54. keyboard.IsKeyDown(Keys.Left))
  55. {
  56. direction |= Left;
  57. }
  58. else if (gamePad.IsButtonDown(Buttons.DPadRight) ||
  59. gamePad.IsButtonDown(Buttons.LeftThumbstickRight) ||
  60. keyboard.IsKeyDown(Keys.Right))
  61. {
  62. direction |= Right;
  63. }
  64. return direction;
  65. }
  66. /// <summary>
  67. /// Gets the direction without non-direction buttons from a set of Buttons flags.
  68. /// </summary>
  69. public static Buttons FromButtons(Buttons buttons)
  70. {
  71. // Extract the direction from a full set of buttons using a bit mask.
  72. return buttons & Any;
  73. }
  74. }
  75. }