unity小技巧:實現(xiàn)物品拖拽,位置交換,背包換格的效果

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MoveItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
//記錄玩家開始拖拽時的位置
private Vector3 vector;
//需要移動物品的位置組件
private RectTransform rectTransform;
//UI事件管理器
private EventSystem _EventSystem;
private GraphicRaycaster gra;
private void Awake()
{
_EventSystem = FindObjectOfType<EventSystem>();
gra = FindObjectOfType<GraphicRaycaster>();
rectTransform = GetComponent<RectTransform>();
}
/// <summary>
/// 開始拖拽時執(zhí)行一次
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
vector = this.transform.position;
}
/// <summary>
/// 拖拽時持續(xù)調(diào)用
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
this.rectTransform.anchoredPosition += eventData.delta;
}
/// <summary>
/// 結(jié)束拖拽時執(zhí)行一次
/// </summary>
/// <param name="eventData"></param>
public void OnEndDrag(PointerEventData eventData)
{
//判斷是否拖拽到格子上
bool isSolt = false;
//保存格子的位置
Vector3 SlotVector = new Vector3();
//通過定義的讀取方法讀取鼠標(biāo)所在位置的UI對象
var list = GraphicRaycaster(Input.mousePosition);
foreach (var item in list)
{
//檢測是否在物品上
if (item.gameObject.tag == "Item")
{
//如果在物品上則執(zhí)行以下代碼
//---交換位置---//
this.rectTransform.position = item.gameObject.transform.position;
item.gameObject.transform.position = vector;
}
//檢測是否在格子上
else if(item.gameObject.tag == "Slot")
{
//如果在格子上則將isSlot設(shè)置為true方便后續(xù)代碼
isSolt = true;
//保存格子位置坐標(biāo)以便切換位置
SlotVector = item.gameObject.transform.position;
}
}
//判斷是否檢測在格子上
if (isSolt)
{
//如果在格子上,則切換到格子上
this.rectTransform.position = SlotVector;
}
else
{
//如果不在格子上,則返回原位置
this.rectTransform.position = vector;
}
}
/// <summary>
/// 定義通過射線讀取所在位置的UI對象
/// </summary>
/// <param name="pos">射線位置</param>
/// <returns>返回讀取的所有UI對象</returns>
private List<RaycastResult> GraphicRaycaster(Vector2 pos)
{
var mPointerEventData = new PointerEventData(_EventSystem);
mPointerEventData.position = pos;
List<RaycastResult> results = new List<RaycastResult>();
gra.Raycast(mPointerEventData, results);
return results;
}
}