unity2d如何实现当拖拽UI到正确位置后不能再被拖拽的代码
时间: 2024-05-05 20:17:54 浏览: 72
Unity 从UI中拖拽对象放置并拖动效果
5星 · 资源好评率100%
感谢您的提问!以下是您需要的代码:
```
using UnityEngine;
using UnityEngine.EventSystems;
public class DragAndDrop : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
private Vector3 initialPosition;
public void OnBeginDrag(PointerEventData eventData)
{
initialPosition = transform.position;
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
float distance = Vector3.Distance(transform.position, initialPosition);
if(distance < 50) // 50 为拖拽的容错距离
{
transform.position = initialPosition;
}
else
{
// 拖拽到正确位置后,禁止再次拖拽
GetComponent<CanvasGroup>().blocksRaycasts = false;
}
}
}
```
当拖拽到正确位置后,代码会禁止再次拖拽。希望能够帮助您!
阅读全文