using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class DraggableUI : MonoBehaviour, IDragHandler, IPointerDownHandler { private RectTransform rectTransform; private Canvas canvas; public RectTransform target; public GameObject button; public bool isDone = false; private bool isLocked = false; private void Awake() { rectTransform = GetComponent(); canvas = GetComponentInParent(); LockDrag(); } public void OnPointerDown(PointerEventData eventData) { // 这里可以添加按下时的逻辑,比如记录初始位置 } 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); move.z = transform.position.z; transform.position = move; } void Update() { float distance = Vector3.Distance(transform.position, target.position); if (distance <= 1 && !isDone) { button.SetActive(true); } else { button.SetActive(false); } } public void LockDrag() { isLocked = true; } public void UnlockDrag() { isLocked = false; } }