61 lines
1.4 KiB
C#
61 lines
1.4 KiB
C#
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.UI;
|
|
|
|
public class DraggableUI : MonoBehaviour, IDragHandler, IPointerDownHandler
|
|
{
|
|
private RectTransform rectTransform;
|
|
private Canvas canvas;
|
|
|
|
public RectTransform target;
|
|
public Button button;
|
|
public bool isDone = false;
|
|
private bool isLocked = false;
|
|
|
|
private void Awake()
|
|
{
|
|
rectTransform = GetComponent<RectTransform>();
|
|
canvas = GetComponentInParent<Canvas>();
|
|
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 && !isLocked)
|
|
{
|
|
button.interactable=true;
|
|
}
|
|
else
|
|
{
|
|
button.interactable=false;
|
|
}
|
|
}
|
|
|
|
public void LockDrag()
|
|
{
|
|
isLocked = true;
|
|
}
|
|
|
|
public void UnlockDrag()
|
|
{
|
|
isLocked = false;
|
|
}
|
|
} |