工作的时候需要实现一个拖拽操作,要求是,当上下拖拽的时候,让点击的东西跟随鼠标,左右的时候进行正常滑动,开始做的时候,架构错了,用事件传递也没有效果,拖拽是基于ScrollBar。

动图
上下进行拖动,左右进行滑动
代码块
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ScrollRectOprate : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[Header("是否在检测")]
public bool isCheck = true;
[Header("是否是水平滑动")]
public bool isHori = false;
[Header("起始位置")]
public Vector2 startPos;
//接口实现
public void OnBeganDrag(PointerEventData eventData)
{
//赋值起始位置
startPos=eventData.position;
//初始关闭水平滑动
GetComponent<ScrollRect>().horizontal=false;
}
public void OnDrag(PointerEventData eventData)
{
//计算偏移
float offsetX = Mathf.Abs(eventData.position.x-startPos.x);
float offsetY = Mathf.Abs(eventData.position.y-startPos.y);
//如果还在检测中
if (isCheck)
{
if (offsetX>3||offsetY>3)
{
//开始赋值
isHori=offsetX>offsetY;
isCheck=false;
//这里需要检测一下是否碰到需要拖拽的物品
//射线检测位置
PointerEventData pointerData = new PointerEventData()
{
//使用起始点击的坐标
position=startPos
};
//存储列表
List<RaycastResult> results = new List<RaycastResult>();
//执行射线检测
EventSystem.current.RaycastAll(pointerData, result);
//开始遍历结果
foreach (var i in results)
{
//这里来获取脚本为例,按需要可以改为tag,名字等等
TestSrc src = i.gameObject.GetComponent<TestSrc>();
if (src!=null)
{
//执行操作,可以把获取的物品暂时存储在这个脚本里面
break;
}
}
}
if (isCheck==false)
{
if (isHori)
{
//开启水平滑动
GetComponent<ScrollRect>().horizontal=true;
}
else
{
//这里可以进行操作,比如让某个物品跟随鼠标移动
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
}
}
public void EndDrag(PointerEventData eventData)
{
//一样可以进行射线检测,来检测此时是不是到达目标物品上面
PointerEventData pointerData = new PointerEventData()
{
//这里需要使用鼠标位置
position=Input.mousePosition
};
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
foreach (var i in results)
{
//这里还是用脚本进行测试
MySrc src = i.gameObject.GetComponent<MySrc>();
if (src!=null)
{
//这里可以进行一些操作,比如,把物品放到目标的位置
}
}
//初始数据
isCheck=true;
isHori=false;
GetComponent<ScrollRect>().horizontal=true;
}
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删