fix(fix-system): 修复拖拽 UI 跳位
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -8,6 +8,8 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IPointerDownHandler
|
||||
public RectTransform target;
|
||||
public Button button;
|
||||
private bool isLocked = false;
|
||||
private Vector3 _dragOffset;
|
||||
private float _dragScreenZ;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
@@ -16,22 +18,34 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IPointerDownHandler
|
||||
|
||||
public void OnPointerDown(PointerEventData eventData)
|
||||
{
|
||||
// 这里可以添加按下时的逻辑,比如记录初始位置
|
||||
if (isLocked) return;
|
||||
|
||||
Camera cam = ResolveCamera(eventData);
|
||||
if (cam == null) return;
|
||||
|
||||
// 记录指针与物体的世界空间偏移,避免拖动开始时物体跳到指针中心。
|
||||
_dragScreenZ = cam.WorldToScreenPoint(transform.position).z;
|
||||
Vector3 pointerWorld = ScreenToWorld(cam, eventData.position, _dragScreenZ);
|
||||
_dragOffset = transform.position - pointerWorld;
|
||||
}
|
||||
|
||||
public void OnDrag(PointerEventData eventData)
|
||||
{
|
||||
if (isLocked) return;
|
||||
|
||||
Vector3 screenPosition = new Vector3(eventData.position.x, eventData.position.y,
|
||||
Camera.main.WorldToScreenPoint(transform.position).z);
|
||||
Vector3 move = Camera.main.ScreenToWorldPoint(screenPosition);
|
||||
Camera cam = ResolveCamera(eventData);
|
||||
if (cam == null) return;
|
||||
|
||||
Vector3 pointerWorld = ScreenToWorld(cam, eventData.position, _dragScreenZ);
|
||||
Vector3 move = pointerWorld + _dragOffset;
|
||||
move.z = transform.position.z;
|
||||
transform.position = move;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (target == null || button == null) return;
|
||||
|
||||
float distance = Vector3.Distance(transform.position, target.position);
|
||||
|
||||
if (distance <= 1 && !isLocked)
|
||||
@@ -53,4 +67,16 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IPointerDownHandler
|
||||
{
|
||||
isLocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Camera ResolveCamera(PointerEventData eventData)
|
||||
{
|
||||
if (eventData != null && eventData.pressEventCamera != null)
|
||||
return eventData.pressEventCamera;
|
||||
return Camera.main;
|
||||
}
|
||||
|
||||
private static Vector3 ScreenToWorld(Camera cam, Vector2 screenPosition, float screenZ)
|
||||
{
|
||||
return cam.ScreenToWorldPoint(new Vector3(screenPosition.x, screenPosition.y, screenZ));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user