2
0

VirtualStick.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using Microsoft.Xna.Framework;
  3. using Microsoft.Xna.Framework.Graphics;
  4. using Microsoft.Xna.Framework.Input.Touch;
  5. namespace FarseerPhysics.SamplesFramework
  6. {
  7. public sealed class VirtualStick
  8. {
  9. private Sprite _socketSprite;
  10. private Sprite _stickSprite;
  11. private int _picked;
  12. private Vector2 _position;
  13. private Vector2 _center;
  14. public Vector2 StickPosition;
  15. public VirtualStick(Texture2D socket, Texture2D stick, Vector2 position)
  16. {
  17. _socketSprite = new Sprite(socket);
  18. _stickSprite = new Sprite(stick);
  19. _picked = -1;
  20. _center = position;
  21. _position = position;
  22. StickPosition = Vector2.Zero;
  23. }
  24. public void Update(TouchLocation touchLocation)
  25. {
  26. if (touchLocation.State == TouchLocationState.Pressed && _picked < 0)
  27. {
  28. Vector2 delta = touchLocation.Position - _position;
  29. if (delta.LengthSquared() <= 2025f)
  30. {
  31. _picked = touchLocation.Id;
  32. }
  33. }
  34. if ((touchLocation.State == TouchLocationState.Pressed ||
  35. touchLocation.State == TouchLocationState.Moved) && touchLocation.Id == _picked)
  36. {
  37. Vector2 delta = touchLocation.Position - _center;
  38. if (delta != Vector2.Zero)
  39. {
  40. float _length = delta.Length();
  41. if (_length > 25f)
  42. {
  43. delta *= (25f / _length);
  44. }
  45. StickPosition = delta / 25f;
  46. StickPosition.Y *= -1f;
  47. _position = _center + delta;
  48. }
  49. }
  50. if (touchLocation.State == TouchLocationState.Released && touchLocation.Id == _picked)
  51. {
  52. _picked = -1;
  53. _position = _center;
  54. StickPosition = Vector2.Zero;
  55. }
  56. }
  57. public void Draw(SpriteBatch batch)
  58. {
  59. batch.Draw(_socketSprite.Texture, _center, null, Color.White, 0f,
  60. _socketSprite.Origin, 1f, SpriteEffects.None, 0f);
  61. batch.Draw(_stickSprite.Texture, _position, null, Color.White, 0f,
  62. _stickSprite.Origin, 1f, SpriteEffects.None, 0f);
  63. }
  64. }
  65. }