using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ButtonOnClick : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
// 按压的持续时间
float pressDurationTime = 1;
// 按压的响应次数
bool responseOnceByPress = false;
// 双击的间隔时间
float doubleClickIntervalTime = 0.5f;
// 拖动的间隔时间
float dragIntervalTime = 0.2f;
// 拖动的鼠标间隔距离
float dragIntervalPos = 0.01f;
/// <summary>
/// 双击事件
/// </summary>
public UnityEvent onDoubleClick;
/// <summary>
/// 按压事件
/// </summary>
public UnityEvent onPress;
/// <summary>
/// 点击事件
/// </summary>
public UnityEvent onClick;
/// <summary>
/// 拖动事件
/// </summary>
public UnityEvent onDrag;
private bool isDown = false;
private bool isPress = false;
private bool isDrag = false;
private float downTime = 0;
private float clickIntervalTime = 0;
private int clickTimes = 0;
private Vector3 mousePosLast = Vector3.zero;//点击后的拖动位置
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("鼠标左键点击");
}
if (isDown)
{
if (responseOnceByPress && isPress)
{
return;
}
downTime += Time.deltaTime;
isDrag = Vector3.Distance(Input.mousePosition, mousePosLast) > dragIntervalPos;
if (downTime > pressDurationTime && !isDrag)
{
isPress = true;
onPress.Invoke();
}
if (downTime > dragIntervalTime && isDrag)
{
onDrag.Invoke();
}
}
if (clickTimes >= 1)
{
clickIntervalTime += Time.deltaTime;
if (clickIntervalTime >= doubleClickIntervalTime)
{
if (clickTimes >= 2)
{
onDoubleClick.Invoke();
}
else
{
onClick.Invoke();
}
clickTimes = 0;
clickIntervalTime = 0;
}
}
}
public void OnPointerClick(PointerEventData eventData)
{
if (!isPress)
clickTimes += 1;
else
isPress = false;
}
public void OnPointerDown(PointerEventData eventData)
{
isDown = true;
downTime = 0;
mousePosLast = Input.mousePosition;
}
public void OnPointerExit(PointerEventData eventData)
{
isDown = false;
isPress = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isDown = false;
}
}
04-25
1195
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-30
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交