Draggable_Window.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using UnityEngine.Events;
  6. using UnityEngine.EventSystems;
  7. public class Draggable_Window : Draggable
  8. {
  9. Vector3 startInputLocalPos = Vector3.zero;
  10. Vector3 startLocalPos = Vector3.zero;
  11. [SerializeField] float minX;
  12. [SerializeField] float maxX;
  13. [SerializeField] float minY;
  14. [SerializeField] float maxY;
  15. [SerializeField] Vector3 defaultPos;
  16. private void OnEnable()
  17. {
  18. transform.localPosition = defaultPos;
  19. }
  20. public override void OnBeginDrag(BaseEventData eventData)
  21. {
  22. startInputLocalPos = GetLocalPosition(Input.mousePosition, this.transform);
  23. startLocalPos = this.self.localPosition;
  24. }
  25. public override void OnDrag(BaseEventData eventData)
  26. {
  27. this.self.localPosition = GetLocalPosition(Input.mousePosition, this.transform) - startInputLocalPos + startLocalPos;
  28. }
  29. public override void OnEndDrag(BaseEventData eventData)
  30. {
  31. while (!isWithinRange())
  32. {
  33. if(minX > this.transform.localPosition.x)
  34. {
  35. this.transform.localPosition += new Vector3(0.1f, 0f);
  36. }
  37. else if (maxX < this.transform.localPosition.x)
  38. {
  39. this.transform.localPosition -= new Vector3(0.1f, 0f);
  40. }
  41. else if (minY > this.transform.localPosition.y)
  42. {
  43. this.transform.localPosition += new Vector3(0f, 0.1f);
  44. }
  45. else if (maxY < this.transform.localPosition.y)
  46. {
  47. this.transform.localPosition -= new Vector3(0f, 0.1f);
  48. }
  49. }
  50. bool isWithinRange()
  51. {
  52. if(minX <= this.transform.localPosition.x && this.transform.localPosition.x <= maxX)
  53. {
  54. if (minY <= this.transform.localPosition.y && this.transform.localPosition.y <= maxY)
  55. {
  56. return true;
  57. }
  58. }
  59. return false;
  60. }
  61. }
  62. }