【Unity】(2D)物体拖拽

在2D场景中,实现将框中的物体拖拽之符合条件的物体中;
应用场景:排序、物品栏、背包等;

成果展示

Demo中实现的效果是画面中存在4个图片,需要按照喜好程度对图片进行排序,将上面的1-2-3-4序号拖拽至对应的图片旁边。

Scene部分

其中Target中存放4张猫咪图片,对应的Content中的1-2-3-4是下面的白色方框。
可以被拖拽的物体绑定组件 Canvas Group,这里对应的是Id

脚本部分

脚本绑定在可以被拖拽的物体上

public class TargetArray : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
{
    [SerializeField] private Canvas canvas;
    [SerializeField] private Transform Parent;
    private RectTransform rectTrans;
    private CanvasGroup canvasGroup;
    Vector3 originalPosition;
    Transform originalParent;
    private void Start()
    {
        rectTrans = GetComponent<RectTransform>();
        canvasGroup = GetComponent<CanvasGroup>();
    }
    public void OnBeginDrag(PointerEventData eventData)
    {
        originalPosition.z = 0;
        originalPosition = transform.position;
        originalParent = transform.parent;
        canvasGroup.blocksRaycasts = false;
        canvasGroup.alpha = 0.35f;
        transform.SetParent(Parent);
    }

    public void OnDrag(PointerEventData eventData)
    {
        rectTrans.anchoredPosition += eventData.delta / canvas.scaleFactor;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        canvasGroup.blocksRaycasts = true;
        canvasGroup.alpha = 1f;

        GameObject itemSlot = eventData.pointerCurrentRaycast.gameObject;
        if (itemSlot != null && itemSlot.CompareTag("slot") && (itemSlot.transform.childCount ==0))
        {
            transform.SetParent(itemSlot.transform);
            transform.position = itemSlot.transform.position;
        }
        else
        {
            transform.position = originalPosition;
            transform.SetParent(originalParent);
        }
    }
}
posted @ 2024-09-30 08:52  Sitar  阅读(31)  评论(0编辑  收藏  举报