實現代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragUI : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
/// <summary>
/// UI和指針的位置偏移量
/// </summary>
Vector3 offset;
RectTransform rt;
Vector3 pos;
float minWidth; //水平最小拖拽範圍
float maxWidth ; //水平最大拖拽範圍
float minHeight; //垂直最小拖拽範圍
float maxHeight; //垂直最大拖拽範圍
float rangeX; //拖拽範圍
float rangeY; //拖拽範圍
void Update()
{
DragRangeLimit();
}
void Start()
{
rt = GetComponent<RectTransform>();
pos = rt.position;
minWidth = rt.rect.width / 2;
maxWidth = Screen.width - (rt.rect.width / 2);
minHeight = rt.rect.height / 2;
maxHeight = Screen.height - (rt.rect.height / 2);
}
/// <summary>
/// 拖拽範圍限制
/// </summary>
void DragRangeLimit()
{
//限制水平/垂直拖拽範圍在最小/最大值內
rangeX = Mathf.Clamp(rt.position.x, minWidth, maxWidth);
rangeY = Mathf.Clamp(rt.position.y, minHeight, maxHeight);
//更新位置
rt.position = new Vector3(rangeX, rangeY, 0);
}
/// <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);
}
/// <summary>
/// 結束拖拽
/// </summary>
public void OnEndDrag(PointerEventData eventData)
{
}
/// <summary>
/// 更新UI的位置
/// </summary>
private void SetDraggedPosition(PointerEventData eventData)
{
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rt, eventData.position, null, out globalMousePos))
{
rt.position = offset + globalMousePos;
}
}
}
拖拽功能的實現:
UGUI實現UI拖拽功能需要繼承IBeginDragHandler, IDragHandler, IEndDragHandler三個接口,並實現接口的三個方法:OnBeginDrag()、OnDrag()、OnEndDrag(),這三個方法分別在開始拖拽、拖拽中、結束拖拽時調用。需要注意的是,即使其中一個方法不執行任何代碼,也必須實現該方法,除非不繼承該方法的接口,例如上述代碼中的OnEndDrag()。
SetDraggedPosition()方法用於更新UI的位置,首先在OnDrag()中計算UI和指針的偏移量,然後將偏移量和轉換成世界座標後的指針位置相加,得到UI的位置。
限制拖拽範圍的實現:
根據UI的寬高和攝像機的可視範圍(Screen.width/height)計算出UI的水平/垂直移動範圍,用Clamp()方法將UI位置的x和y值鎖定在水平/垂直移動範圍內。
腳本使用方法,直接把腳本添加到需要拖拽的UI上即可。