76 lines
1.9 KiB
Plaintext
76 lines
1.9 KiB
Plaintext
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using UnityEngine.EventSystems;
|
|
using System.Collections;
|
|
using System;
|
|
|
|
public class ButtonInteraction : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler
|
|
{
|
|
[SerializeField]
|
|
private Sprite m_pressSprite;
|
|
[SerializeField]
|
|
private Sprite m_normalSprite;
|
|
[SerializeField]
|
|
private Image m_image;
|
|
private bool isPointerDown = false;
|
|
private float pointerDownTimer = 0f;
|
|
private float requiredHoldTime = 1.0f; // 长按所需时间
|
|
Coroutine shakeCor;
|
|
|
|
private Action ClickAction;
|
|
public void Init(Action ClickAc)
|
|
{
|
|
ClickAction = ClickAc;
|
|
}
|
|
|
|
public void OnPointerDown(PointerEventData eventData)
|
|
{
|
|
Debug.Log("OnPointerDown");
|
|
isPointerDown = true;
|
|
if(m_image!=null){m_image.sprite = m_pressSprite;}
|
|
if(shakeCor!=null)StopCoroutine(shakeCor);
|
|
shakeCor = StartCoroutine(DelayShake());
|
|
}
|
|
|
|
public void OnPointerUp(PointerEventData eventData)
|
|
{
|
|
Reset();
|
|
if(m_image!=null){m_image.sprite = m_normalSprite;}
|
|
if(shakeCor!=null)StopCoroutine(shakeCor);
|
|
ClickAction();
|
|
Debug.Log("OnPointerUp");
|
|
}
|
|
|
|
public void OnPointerClick(PointerEventData eventData)
|
|
{
|
|
// 处理点击事件
|
|
Debug.Log("Click");
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (isPointerDown)
|
|
{
|
|
pointerDownTimer += Time.deltaTime;
|
|
if (pointerDownTimer >= requiredHoldTime)
|
|
{
|
|
// 处理长按事件
|
|
Debug.Log("Long Press");
|
|
Reset();
|
|
}
|
|
}
|
|
}
|
|
|
|
private void Reset()
|
|
{
|
|
isPointerDown = false;
|
|
pointerDownTimer = 0f;
|
|
}
|
|
|
|
IEnumerator DelayShake()
|
|
{
|
|
HandheldUtils.Vibrate();
|
|
yield return new WaitForSeconds(1f);
|
|
shakeCor = StartCoroutine(DelayShake());
|
|
}
|
|
} |