首先看一下效果
附上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class UIDrag : UIBase, IBeginDragHandler, IDragHandler, IEndDragHandler, IPointerClickHandler
{
private bool isDrag;
private RectTransform rect;
private Vector2 tempPos;
private Vector3 offset = Vector3.zero;
//private static int index = 0;
public void OnBeginDrag(PointerEventData eventData)
{
SetIndex();
isDrag = false;
SetDragObjPostion(eventData);
}
public void OnDrag(PointerEventData eventData)
{
isDrag = true;
SetDragObjPostion(eventData);
}
void SetDragObjPostion(PointerEventData eventData)
{
RectTransform rect = this.GetComponent<RectTransform>();
Vector3 mouseWorldPosition;
//判断是否点到UI图片上的时候
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rect, eventData.position, eventData.pressEventCamera,
out mouseWorldPosition))
{
if (isDrag)
{
rect.position = mouseWorldPosition + offset;
}
else
{
//计算偏移量
offset = rect.position - mouseWorldPosition;
}
}
}
void IEndDragHandler.OnEndDrag(PointerEventData eventData)
{
//isDrag = false;
}
public void SetIndex()
{
gameObject.transform.SetAsLastSibling();
}
public void OnPointerClick(PointerEventData eventData)
{
SetIndex();
}
}