[Unity小技巧] 避免手机触屏连续多次触发触摸touch事件

本文介绍如何在Unity中实现手机游戏触屏事件的一次点击仅响应一次。通过设置布尔变量touchingScreen跟踪触屏状态,并结合Input.touchCount判断,确保在Update()函数中正确响应触摸事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多同学在用Unity做手机游戏开发的时候,都会遇到这样一个问题:在Update()函数里检测屏幕触摸事件并作出响应,但是在手机上实际运行的时候,手指点击屏幕的时候,会连续响应多次触摸(touch)事件。原因是Update()函数在我们手指触摸屏幕到手指离开屏幕这段时间之间调用了多次。像下面:



然而实际开发时,我们更多的需求是:点击一次屏幕,只响应一次触摸事件。怎么解决这个问题呢?


我的思路是:

       1、设置一个触屏检测的bool变量touchingScreen,true为正在触屏。

       2、在Update()函数里根据Input.touchCount来判断:当Input.touchCount <= 0,设置touchingScreen为false(即没触屏);当Input.touchCount > 0,只有touchingScreen为false才可以进行触摸响应,第一次触摸响应时将touchingScreen设为true(正在触屏,则接下来调用Update()函数时,因为touchingScreen为true所以不可以进行触摸响应)。


代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TestScript : MonoBehaviour {
    private string debugText = "DebugText: \n";
    private GameObject DebugText;
    private GameObject Button;
    private int timeCount;
    private bool touchingScreen;   //true为touching

    void Start () {
        DebugText = GameObject.Find("DebugText");
        Button = GameObject.Find("Button");
        DebugText.GetComponent<Text>().text = debugText;
        timeCount = 1;
        touchingScreen = false;
    }
	
    void Update () {
        if (Input.touchCount > 0) {
            // 检测哪些按钮正被按下
            for (int i = 0; i < Input.touchCount; i++) {
                Vector3 touchWorldPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
                touchWorldPosition.z = 0;
                if (!touchingScreen && Button != null) {   // 第一次响应触屏事件
                    touchingScreen = true;
                    if (Vector3.Distance(touchWorldPosition, Button.transform.position) < 1) {
                        debugText += "Touching the screen and response " + timeCount + "\n";
                        DebugText.GetComponent<Text>().text = debugText;
                    }
                }
            }
        }
        else {
            touchingScreen = false;
        }

        // 退出
        if (Input.GetKeyDown(KeyCode.Escape)) {
            Application.Quit();
        }
    }
}


好了,最后的效果变成下面这样,即点击一次屏幕只响应一次的触摸touch事件:



这样就解决了一次触屏响应多次触摸事件的问题啦~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值