Clickable.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. readonly Rectangle rectangle;
  14. bool wasTouching;
  15. bool isTouching;
  16. public bool IsTouching { get { return isTouching; } }
  17. public bool IsClicked { get { return (wasTouching == true) && (isTouching == false); } }
  18. protected Rectangle Rectangle { get { return rectangle; } }
  19. protected new Graphics3DSampleGame Game { get { return (Graphics3DSampleGame)base.Game; } }
  20. /// <summary>
  21. /// Constructor
  22. /// </summary>
  23. /// <param name="game">The Game oject</param>
  24. /// <param name="targetRectangle">Position of the component on the screen</param>
  25. public Clickable(Graphics3DSampleGame game, Rectangle targetRectangle)
  26. : base(game)
  27. {
  28. rectangle = targetRectangle;
  29. }
  30. /// <summary>
  31. /// Handles Input
  32. /// </summary>
  33. protected void HandleInput()
  34. {
  35. wasTouching = isTouching;
  36. isTouching = false;
  37. TouchCollection touches = TouchPanel.GetState();
  38. if (touches.Count > 0)
  39. {
  40. var touch = touches[0];
  41. var position = touch.Position;
  42. Rectangle touchRect = new Rectangle((int)touch.Position.X - 5, (int)touch.Position.Y - 5,
  43. 10, 10);
  44. if (rectangle.Intersects(touchRect))
  45. isTouching = true;
  46. }
  47. }
  48. }
  49. }