Unity 适用Canvas 为任一渲染模式的UI 拖拽
RectTransformUtility-ScreenPointToWorldPointInRectangle - Unity 脚本 API
将一个屏幕空间点转换为世界空间中位于给定RectTransform 平面上的一个位置。
实现
获取平面位置。
parentRT = transform.parent as RectTransform;
继承IPointerDownHandler 和IDragHandler 接口。
鼠标点击时记录鼠标与UI 位置的偏差。
RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRT, eventData.position, eventData.pressEventCamera, out Vector3 worldPoint);
offset = transform.position - worldPoint;
拖拽时记录鼠标位置并设定UI 位置。
RectTransformUtility.ScreenPointToWorldPointInRectangle(parentRT, eventData.position, eventData.pressEventCamera, out Vector3 worldPoint);
transform.position = worldPoint + offset;