Unity实现背包拖拽功能 可以实现背包拖拽交换位置、合成 等一系列功能的实现文章来源地址https://www.toymoban.com/news/detail-529913.html
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class DragCtrl : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler, ICanvasRaycastFilter
{
public GradeItem item;
private Transform nowparent;
private bool isRaycastLocationValid = true;//默认射线不能穿透物体
public Transform IconList;//存放拖拽物体的公共节点
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
{
return isRaycastLocationValid;
}
/// <summary>
/// 开始拖动
/// </summary>
/// <param name="eventData"></param>
public void OnBeginDrag(PointerEventData eventData)
{
OClickBtn();
this.transform.SetAsLastSibling();//将被拖拽的物体设置为最后渲染
nowparent = this.transform.parent;//保存最初始的位置
isRaycastLocationValid = false;//设置射线穿透
transform.SetParent(IconList);//将拖拽的物体放在公共父节点下
//下面可以放拖拽时的功能
}
/// <summary>
/// 拖动中
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
Vector2 v2 = Vector2.zero;
RectTransformUtility.ScreenPointToLocalPointInRectangle(IconList.GetComponent<RectTransform>(), Input.mousePosition,StaffUIMgr.instance.mCamera, out v2);将拖拽时的屏幕坐标转换为公共节点下的局部坐标,不转换将看不见拖拽物体
transform.localPosition = v2;
}
/// <summary>
/// 拖动结束
/// </summary>
/// <param name="eventData"></param>
/// <exception cref="System.NotImplementedException"></exception>
public void OnEndDrag(PointerEventData eventData)
{
//transform.Find("Select").gameObject.SetActive(false);
GameObject go = eventData.pointerCurrentRaycast.gameObject;
if(go != null)
{
if (go.transform.parent.name == "iconItem")
{
//放拖动结束需要实现的功能
}
else
{
//拖动失败 拖动物体复原
transform.SetParent(nowparent);
transform.position = nowparent.position;
}
}
else
{
//拖动失败 拖动物体复原
transform.SetParent(nowparent);
transform.position = nowparent.position;
}
isRaycastLocationValid = true;//射线不可以穿透物体
}
文章来源:https://www.toymoban.com/news/detail-529913.html
到了这里,关于【Unity实现背包拖拽功能 】的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!