纳金网
标题:
uGUI长按事件的代码
[打印本页]
作者:
王者再临
时间:
2015-7-30 22:24
标题:
uGUI长按事件的代码
突然发现uGUI没有给出可以直接用的长按事件。。。
上个没有注释的代码,代码说明一切。
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class UILongPressEvent : MonoBehaviour,IPointerDownHandler,IPointerExitHandler,IPointerUpHandler
{
[SerializeField]
UnityEvent m_onLongPress = new UnityEvent();
float interval = 0.1f;
float longPressDelay = 0.5f;
private bool isTouchDown = false;
private bool isLongpress = false;
private float touchBegin = 0;
private float lastInvokeTime = 0;
// Update is called once per frame
void Update ()
{
if (isTouchDown)
{
if (isLongpress)
{
if (Time.time - lastInvokeTime > interval)
{
m_onLongPress.Invoke();
lastInvokeTime = Time.time;
}
}
else
{
if (Time.time - touchBegin > longPressDelay)
{
isLongpress = true;
}
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
touchBegin = Time.time;
isTouchDown = true;
}
public void OnPointerExit(PointerEventData eventData)
{
isTouchDown = false;
isLongpress = false;
}
public void OnPointerUp(PointerEventData eventData)
{
isTouchDown = false;
isLongpress = false;
}
}
复制代码
反正都写了,顺便给下NGUI的长按吧。
NGUI的可以监听onPress事件;
bool pressMinus = false;
bool pressPlus = false;
void LongPressMinus(GameObject sender, bool state)
{
pressMinus = state;
if (state)
{
StartCoroutine(ExcuteLongMinus());
}
else
{
CancelInvoke();
}
}
void LongPressPlus(GameObject sender, bool state)
{
pressPlus = state;
if (state)
{
StartCoroutine(ExcuteLongPlus());
}
else
{
CancelInvoke();
}
}
IEnumerator ExcuteLongMinus() {
yield return new WaitForSeconds(0.8f);
if (pressMinus)
{
InvokeRepeating("MinusTimes", 0, 0.1f);
}
}
IEnumerator ExcuteLongPlus() {
yield return new WaitForSeconds(0.8f);
if (pressPlus)
{
InvokeRepeating("PlusTimes", 0, 0.1f);
}
}
复制代码
欢迎光临 纳金网 (http://go.narkii.com/club/)
Powered by Discuz! X2.5