首先是拖拽我们的panel
1.打开Unity新建场景,在Hierarchy面板上新建panel。
2.调整锚点如图并更改大小。
3.代码时间,挂在panel上就可以了,点击panel任意位置都可以移动哦。
using UnityEngine;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour,IBeginDragHandler,IDragHandler{
Vector3 offset;
RectTransform rt;
void Start()
{
rt = GetComponent<RectTransform>();
}
/// <summary>
/// 开始拖拽
/// </summary>
public void OnBeginDrag(PointerEventData eventData)
{
Vector3 globalMousePos;
//将屏幕坐标转换为世界坐标
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
//计算UI和指针之间的位置偏移量
offset = rt.position - globalMousePos;
}
}
/// <summary>
/// 拖拽中
/// </summary>
public void OnDrag(PointerEventData eventData)
{
SetDraggedPosition(eventData);
}
private void SetDraggedPosition(PointerEventData eventData)
{
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
rt.position = offset + globalMousePos;
}
}
}
现在我们完成了拖拽的功能,但是没有限制它的一个范围,可能出现拖到game视图外的情况。
4.加入范围
using UnityEngine;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour,IBeginDragHandler,IDragHandler{
Vector3 offset;
RectTransform rt;
float minWidth;//水平最小拖拽范围
float maxWidth