using System.Runtime.InteropServices.WindowsRuntime; using Rokid.UXR.Interaction; using UnityEngine; using UnityEngine.EventSystems; namespace Rokid.UXR.Components { public class BezierDragUI : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler, IBezierCurveDrag { [SerializeField] public RectTransform canvas;//得到canvas的ugui坐标 private RectTransform imgRect; private Vector2 offset;//临时记录点击点与UI的相对位置 private bool IsDraging; void Start() { //初始化组件 imgRect = GetComponent(); } public void OnDrag(PointerEventData eventData) { // UnityEngine.RKLog.Info("On Drag"); Vector2 mouseDrag = eventData.position; //当鼠标拖动时的屏幕坐标 Vector2 uguiPos; //用来接收转换后的拖动坐标 bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDrag, eventData.enterEventCamera, out uguiPos); if (isRect && Mathf.Abs(uguiPos.x) < Screen.width && Mathf.Abs(uguiPos.y) < Screen.height) { //设置图片的ugui坐标与鼠标的ugui坐标保持不变 if (!UseBezierCurve) { imgRect.anchoredPosition = offset + uguiPos; } else { anchoredPos = offset + uguiPos; } } } public void OnBeginDrag(PointerEventData eventData) { IsDraging = true; // 保存点击点的坐标 HitPoint = transform.InverseTransformPoint(eventData.pointerCurrentRaycast.worldPosition); //开始拖拽 //这里必须先更换父物体否则,offset会计算出问题 Vector2 mouseDown = eventData.position; Vector2 mouseUguiPos; bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, mouseDown, eventData.enterEventCamera, out mouseUguiPos); if (isRect && Mathf.Abs(mouseUguiPos.x) < Screen.width && Mathf.Abs(mouseUguiPos.y) < Screen.height) { offset = imgRect.anchoredPosition - mouseUguiPos; } else { offset = imgRect.anchoredPosition; } } public void OnEndDrag(PointerEventData eventData) { RKLog.Info("On End Drag"); IsDraging = false; } #region BezierCurve [SerializeField] private bool UseBezierCurve = true; [SerializeField] private float moveLerpTime = 0.05f; private Vector3 HitPoint; private Vector2 anchoredPos; public bool IsEnablePinchBezierCurve() { return UseBezierCurve; } public bool IsEnableGripBezierCurve() { return false; } public bool IsInBezierCurveDragging() { return IsDraging; } public Vector3 GetBezierCurveEndPoint() { return transform.TransformPoint(HitPoint); } private void Update() { if (UseBezierCurve && IsDraging) { imgRect.anchoredPosition = Vector2.Lerp(imgRect.anchoredPosition, anchoredPos, 1f - Mathf.Pow(moveLerpTime, Time.deltaTime)); } } public Vector3 GetBezierCurveEndNormal() { return transform.forward; } #endregion } }