From 305d6a71f2009e96bffeb7f2690a47e59a67d509 Mon Sep 17 00:00:00 2001 From: bottlefish <781230111@qq.com> Date: Sun, 26 Jul 2026 23:44:10 +0800 Subject: [PATCH] =?UTF-8?q?fix(fix-system):=20=E4=BF=AE=E5=A4=8D=E6=8B=96?= =?UTF-8?q?=E6=8B=BD=20UI=20=E8=B7=B3=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- Assets/Scripts/FixSystem/DraggableUI.cs | 36 +++++++++++++++++++++---- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/Assets/Scripts/FixSystem/DraggableUI.cs b/Assets/Scripts/FixSystem/DraggableUI.cs index 5d1266018..d4265aacb 100644 --- a/Assets/Scripts/FixSystem/DraggableUI.cs +++ b/Assets/Scripts/FixSystem/DraggableUI.cs @@ -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; } -} \ No newline at end of file + + 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)); + } +}