using UnityEngine;
using UnityEngine.EventSystems;
public class DragUIEvent : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler
{
public RectTransform canvas; //得到canvas的ugui坐标
private RectTransform rt; //得到拖拽图片的ugui坐标
Vector2 offset=new Vector3(); //用来得到鼠标点击和图片的差值
Vector2 CenterPos; //用来得到将屏幕高宽转换为UI坐标高宽
void Start()
{
rt = GetComponent<RectTransform>();
canvas =transform.parent .GetComponent<RectTransform>();
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas , new Vector2(Screen.width,Screen.height), null, out CenterPos);
}
public void OnBeginDrag(PointerEventData eventData)
{
//两种坐标转换方式都可以
/*
Vector3 globalMousePos;
//将屏幕坐标转换成世界坐标
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
//计算UI和指针之间的位置偏移量
//offset = rt.position - globalMousePos;
}
*/
Vector2 mouseUguiPos;//定义一个接收返回的ugui坐标
if(RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, eventData.position, eventData.enterEventCamera, out mouseUguiPos))
{
offset = rt.anchoredPosition - mouseUguiPos;
}
}
/// <summary>
/// 拖拽范围限制
/// </summary>
private void DragRangeLimit()
{
var minX = -CenterPos.x+rt.rect.width/ 2;
var maxX = CenterPos.x-rt.rect.width/ 2;
var Pos = rt.anchoredPosition;
if (Pos.x < minX)
{
Pos.x = minX;
}
else if (Pos.x > maxX)
{
Pos.x = maxX;
}
var minY = -CenterPos.y+rt.rect.height/ 2;
var maxY = CenterPos.y-rt.rect.height/ 2;
if (Pos.y < minY)
{
Pos.y = minY;
}
else if (Pos.y > maxY)
{
Pos.y = maxY;
}
rt.anchoredPosition = Pos;
}
public void OnDrag(PointerEventData eventData)
{
if (eventData != null)
{
/*
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
//计算UI和指针之间的位置偏移量
//rt.position= offset + globalMousePos;
}
*/
Vector2 mouseUguiPos;//定义一个接收返回的ugui坐标
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, eventData.position, eventData.enterEventCamera, out mouseUguiPos))
{
rt.anchoredPosition= offset + mouseUguiPos;
}
//注释 bool isRect = RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas, eventData.position, eventData.enterEventCamera, out mouseUguiPos);
//RectTransformUtility.ScreenPointToLocalPointInRectangle():把屏幕坐标转化成ugui坐标
//canvas:坐标要转换到哪一个物体上,这里img父类是Canvas,我们就用Canvas
//eventData.enterEventCamera:这个事件是由哪个摄像机执行的
//out mouseUguiPos:返回转换后的ugui坐标
//isRect:方法返回一个bool值,判断鼠标按下的点是否在要转换的物体上
}
DragRangeLimit();
}
public void OnEndDrag(PointerEventData eventData)
{
offset = Vector3.zero;
}