CUI_draggable.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine.UI;
  5. using UnityEngine.EventSystems;
  6. namespace CurvedUI
  7. {
  8. /// <summary>
  9. /// This component enables accurate object dragging over curved canvas. It supports both mouse and gaze controllers. Add it to your canvas object with image component.
  10. /// </summary>
  11. public class CUI_draggable : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
  12. {
  13. Vector2 savedVector;
  14. bool isDragged = false;
  15. public void OnBeginDrag(PointerEventData data)
  16. {
  17. Debug.Log("OnBeginDrag");
  18. Vector2 newPos = Vector2.zero;
  19. RaycastPosition(out newPos);
  20. //save distance from click point to object center to allow for precise dragging
  21. savedVector = new Vector2((transform as RectTransform).localPosition.x, (transform as RectTransform).localPosition.y) - newPos;
  22. isDragged = true;
  23. }
  24. public void OnDrag(PointerEventData data) { }
  25. public void OnEndDrag(PointerEventData data)
  26. {
  27. Debug.Log("OnEndDrag");
  28. isDragged = false;
  29. }
  30. void LateUpdate()
  31. {
  32. if (!isDragged) return;
  33. Debug.Log("OnDrag");
  34. //drag the transform along the mouse. We use raycast to determine its position on curved canvas.
  35. Vector2 newPos = Vector2.zero;
  36. RaycastPosition(out newPos);
  37. //add our initial distance from objects center
  38. (transform as RectTransform).localPosition = newPos + savedVector;
  39. }
  40. void RaycastPosition(out Vector2 newPos)
  41. {
  42. if (CurvedUIInputModule.ControlMethod == CurvedUIInputModule.CUIControlMethod.MOUSE)
  43. {
  44. //position when using mouse
  45. GetComponentInParent<CurvedUISettings>().RaycastToCanvasSpace(Camera.main.ScreenPointToRay(Input.mousePosition), out newPos);
  46. }
  47. else if (CurvedUIInputModule.ControlMethod == CurvedUIInputModule.CUIControlMethod.GAZE)
  48. {
  49. //position when using gaze - uses the center of the screen as guiding point.
  50. GetComponentInParent<CurvedUISettings>().RaycastToCanvasSpace(Camera.main.ScreenPointToRay(new Vector2(Screen.width / 2.0f, Screen.height / 2.0f)), out newPos);
  51. }
  52. else newPos = Vector2.zero;
  53. }
  54. }
  55. }