Clickable.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Input.Touch;
  3. namespace Graphics3DSample
  4. {
  5. /// <summary>
  6. /// A game component.
  7. /// Has an associated rectangle.
  8. /// Accepts touch and click inside the rectangle.
  9. /// Has a state of IsTouching and IsClicked.
  10. /// </summary>
  11. public class Clickable : DrawableGameComponent
  12. {
  13. #region Fields
  14. readonly Rectangle rectangle;
  15. bool wasTouching;
  16. bool isTouching;
  17. #region Protected accessors
  18. public bool IsTouching { get { return isTouching; } }
  19. public bool IsClicked { get { return (wasTouching == true) && (isTouching == false); } }
  20. protected Rectangle Rectangle { get { return rectangle; } }
  21. protected new Graphics3DSampleGame Game { get { return (Graphics3DSampleGame)base.Game; } }
  22. #endregion
  23. #endregion
  24. #region Initialization
  25. /// <summary>
  26. /// Constructor
  27. /// </summary>
  28. /// <param name="game">The Game oject</param>
  29. /// <param name="targetRectangle">Position of the component on the screen</param>
  30. public Clickable(Graphics3DSampleGame game, Rectangle targetRectangle)
  31. : base(game)
  32. {
  33. rectangle = targetRectangle;
  34. }
  35. #endregion
  36. #region Input handling
  37. /// <summary>
  38. /// Handles Input
  39. /// </summary>
  40. protected void HandleInput()
  41. {
  42. wasTouching = isTouching;
  43. isTouching = false;
  44. TouchCollection touches = TouchPanel.GetState();
  45. if (touches.Count > 0)
  46. {
  47. var touch = touches[0];
  48. var position = touch.Position;
  49. Rectangle touchRect = new Rectangle((int)touch.Position.X - 5, (int)touch.Position.Y - 5,
  50. 10, 10);
  51. if (rectangle.Intersects(touchRect))
  52. isTouching = true;
  53. }
  54. }
  55. #endregion
  56. }
  57. }