【Unity】(2D)物體拖拽

Sitar發表於2024-09-30

在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);
        }
    }
}

相關文章