1. 程式人生 > >Unity -- 物品揹包的物品拖動指令碼示例

Unity -- 物品揹包的物品拖動指令碼示例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragGridHelper : MonoBehaviour,IBeginDragHandler, IDragHandler, IEndDragHandler
{


    public void OnBeginDrag(PointerEventData eventData)
    {
        //獲取格子中的物品
        if(transform.childCount > 0)
        {
            Transform child = transform.GetChild(0);
            eventData.selectedObject = child.gameObject;
            Canvas vanvas = child.GetComponent<Canvas>();//每個可以拖動的物體需要有canvas 元件 以調節顯示層級
            vanvas.sortingOrder = vanvas.sortingOrder + 1;//避免遮擋
        }
        
    }


    public void OnDrag(PointerEventData eventData)
    {
        if (eventData.selectedObject != null)
        
        {
            eventData.selectedObject.transform.position = Input.mousePosition;//物體隨滑鼠移動
          
        }
    }


    public void OnEndDrag(PointerEventData eventData)
    {
        if (eventData.selectedObject != null)
        {
            //如果拖拽到了外面 或者停留的地方不是grid
            if (eventData.pointerEnter == null || eventData.pointerEnter.tag != "grid")
            {
                //還原到初始位置
                eventData.selectedObject.transform.SetParent(eventData.pointerDrag.transform);
                //清零本地座標值
                eventData.selectedObject.transform.localPosition = Vector2.zero;
                return;
            }

             //如果當前停留的地方是格子
            if(eventData.pointerEnter.tag == "grid")
            {
                //判斷當前格子是否已經存在物體
                if(eventData.pointerEnter.transform.childCount == 0)
                {
                    //設定拖動物體的父元件為當前格子
                    eventData.selectedObject.transform.SetParent(eventData.pointerEnter.transform);
      
                }
                else //當前格子已經存放物體了
                {
                   //獲取當前格子的物體
                    Transform item = eventData.pointerEnter.transform.GetChild(0);
                    //把當前格子的物體放到拖動物體的格子中
                    item.SetParent(eventData.pointerDrag.transform);
                    //清零本地座標值
                    item.localPosition = Vector2.zero;
                    //設定拖動物體的父元件為當前格子
                    eventData.selectedObject.transform.SetParent(eventData.pointerEnter.transform);

                }

                //清零理拖動物體的本地座標值
                eventData.selectedObject.transform.localPosition = Vector2.zero;
                //還原vanvas.sortingOrder值
                Canvas vanvas = eventData.selectedObject.GetComponent<Canvas>();
                vanvas.sortingOrder = vanvas.sortingOrder - 1;
            }
        }
    }


    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}