版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33000225/article/details/54618584
很多同学在用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();
}
}
}
这样就解决了一次触屏响应多次触摸事件的问题啦~~~