81 lines
2.0 KiB
C#
81 lines
2.0 KiB
C#
using UnityEngine;
|
||
using UnityEngine.Events;
|
||
using UnityEngine.EventSystems;
|
||
/// <summary>
|
||
/// 接受拖动操作的Ui底层组件,Unity原生接口需要额外处理一些释放的问题
|
||
/// </summary>
|
||
public class UiDragComponent : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
|
||
{
|
||
/// <summary>
|
||
/// 当前操作的手指Id
|
||
/// </summary>
|
||
public int? CurrentPointerId { get; private set; }
|
||
/// <summary>
|
||
/// 上次移动的缓存位置
|
||
/// </summary>
|
||
public Vector2 lastPoint { get; private set; }
|
||
/// <summary>
|
||
/// 手指从一点移动到下一点
|
||
/// </summary>
|
||
public event UnityAction<Vector2, Vector2> onDrag;
|
||
/// <summary>
|
||
/// 手指按下操作
|
||
/// </summary>
|
||
public event UnityAction<Vector2> onPress;
|
||
/// <summary>
|
||
/// 手指抬起操作
|
||
/// </summary>
|
||
public event UnityAction<Vector2> onUp;
|
||
|
||
private void OnDisable()
|
||
{
|
||
Release();
|
||
}
|
||
|
||
private void OnApplicationFocus(bool hasFocus)
|
||
{
|
||
if (!hasFocus)
|
||
Release();
|
||
}
|
||
|
||
public void OnPointerDown(PointerEventData eventData)
|
||
{
|
||
if (CurrentPointerId == null)
|
||
{
|
||
CurrentPointerId = eventData.pointerId;
|
||
lastPoint = eventData.position;
|
||
if (onPress != null)
|
||
onPress(lastPoint);
|
||
}
|
||
}
|
||
|
||
public void OnDrag(PointerEventData eventData)
|
||
{
|
||
if (CurrentPointerId == eventData.pointerId)
|
||
{
|
||
if (onDrag != null)
|
||
onDrag(lastPoint, eventData.position);
|
||
lastPoint = eventData.position;
|
||
}
|
||
}
|
||
|
||
public void OnPointerUp(PointerEventData eventData)
|
||
{
|
||
if (CurrentPointerId == eventData.pointerId)
|
||
{
|
||
lastPoint = eventData.position;
|
||
Release();
|
||
}
|
||
}
|
||
|
||
public void Release()
|
||
{
|
||
var temp = CurrentPointerId;
|
||
CurrentPointerId = null;
|
||
if (temp != null)
|
||
{
|
||
if (onUp != null)
|
||
onUp(lastPoint);
|
||
}
|
||
}
|
||
} |