Unity2d android检测触摸

问题描述 投票:0回答:1

如何检测统一的按钮上的触摸和长按,适用于Android?我已经尝试过此功能,但是如果我触摸屏幕上的任何位置,它将返回true:

bool checkTouch()
    {
        for(int i = 0; i < Input.touchCount; i++)
        {
            TouchPhase tp = Input.GetTouch(i).phase;
          if(tp == TouchPhase.Began || tp == TouchPhase.Ended || tp == TouchPhase.Stationary)
            return true;  
        }
        return false;
    }
android unity3d 2d
1个回答
0
投票

实现按钮的一种方法是创建自己的按钮,并实现必要的接口,例如IPointerDownHandler, IPointerUpHandler

这样您可以管理按钮的行为,下面是一个示例:

using UnityEngine;
using UnityEngine.EventSystems;

public class LongClickButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool pointerDown;
    private float pointerDownTimer;

    [SerializeField]
    private float requiredHoldTime;    

    public void OnPointerDown(PointerEventData eventData)
    {
        pointerDown = true;
        Debug.Log("OnPointerDown");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Reset();
        Debug.Log("OnPointerUp");
    }

    private void Update()
    {
        if (pointerDown)
        {
            pointerDownTimer += Time.deltaTime;
            if (pointerDownTimer >= requiredHoldTime)
            {
                //do your LongClick stuff
                Debug.Log("LongClick");
                Reset();
            }
        }
    }

    private void Reset()
    {
        pointerDown = false;
        pointerDownTimer = 0;
    }    
}

[记住将脚本附加到可以是interactable的游戏对象,例如Image

© www.soinside.com 2019 - 2024. All rights reserved.