unity项目中经常需要进行和输入设备的交互,以下是处理事件的一个模块化组件
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class EventTriggerListener : UnityEngine.EventSystems.EventTrigger
{
public delegate void VoidDelegate(GameObject go);
public VoidDelegate onClick;
public VoidDelegate onDbClick;
public VoidDelegate onLongClick;
private bool first = false;
private float interval = 0.3f;
private float timer = 0.0f;
public float durationThreshold = 5.0f;
private bool isPointerDown = false;//鼠标左键是否按下
private bool longPressTriggered = false;//长按触发
private float timePressStarted;//LongClick开始时间
void Update()
{
if (first) {
timer += Time.deltaTime;
if (timer > interval && !longPressTriggered) {
timer = 0;
if (onClick != null)
onClick(gameObject);
first = false;
}
}
if (!longPressTriggered && isPointerDown && (Time.time - timePressStarted) > durationThreshold)
{
longPressTriggered = true;
if (onLongClick != null)
onLongClick(gameObject);
}
}
static public EventTriggerListener Get(GameObject go)
{
EventTriggerListener listener = go.GetComponent<EventTriggerListener>();
if (listener == null) listener = go.AddComponent<EventTriggerListener>();
return listener;
}
public override void OnPointerClick(PointerEventData eventData)
{
if (eventData.button != PointerEventData.InputButton.Left) return;
if (first) {
if (onDbClick != null)
onDbClick(gameObject);
first = false;
timer = 0.0f;
return;
}
first = true;
}
public override void OnPointerDown(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
timePressStarted = Time.time;
isPointerDown = true;
longPressTriggered = false;
}
}
public override void OnPointerExit(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
isPointerDown = false;
}
}
public override void OnPointerUp(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
isPointerDown = false;
}
}
}