首页 > 解决方案 > 触摸屏,如何调整我的代码以仅对一根手指做出反应

问题描述

我正在尝试为我的安卓手机游戏添加有限的触摸屏控件。我一直在看所有这些教程,但我只是没有得到简单的部分之一,至少我认为它很简单。在我的手机上,当你用手指点击它时,我有一辆向左行驶的卡车。当我再次点击它时,我希望它正确。每次点击屏幕时,它都应该朝另一个方向移动,左右交替。它现在很有效,但不是真的。当你第一次点击它时,它会向左移动。但是为了让它正确,你必须用一根手指按住屏幕,然后用第二根手指触摸它。我只想让它一次只对一根手指做出反应,这样你就可以用一只手弹奏它。所以这是我的代码。我究竟做错了什么?我如何解决它?谢谢大家。

试图摆脱回报。尝试根据其他教程调整现有代码并在其中添加其他内容。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class playerController : MonoBehaviour { 

private Rigidbody rb;
private Animator anim;
private bool left = false;
private bool right = false;
public static bool detect = false;
public float yspeed; //left or right from camera's vp
public float xSpeed = 55f; //down the road from camera's vp
[HideInInspector]
public bool crash = false;
public int slowSpeed;
private float respawnTimer = 3f;

void Start () {
    rb = GetComponent<Rigidbody> ();
    anim = GetComponent<Animator> ();
    rb.velocity = new Vector3 (xSpeed, rb.velocity.y, rb.velocity.z);
}


void Update () {    

    Movement ();
    Halt ();
}

public void Movement()
{
    if (crash) {
        left = false;
        right = false;
        scoreManager.scoreValue = 0;
    }
    detect = false;



    if (Input.touchCount > 0 && !left) {
        foreach (Touch touch in Input.touches) {
            rb.velocity = new Vector3 (rb.velocity.x, yspeed, 0);
            left = true;
            right = false;
            return;
        }
    }

        if (Input.touchCount > 0 && !right) {
            foreach (Touch touch in Input.touches) {
                rb.velocity = new Vector3 (rb.velocity.x, -yspeed, 0);
                right = true;
                left = false;
            return;
        }
    }
}

void OnTriggerEnter (Collider other)
{
    if (!crash && other.gameObject.tag == ("wall")) {
        crash = true;
        anim.SetTrigger ("crash");
    }

}
public void Halt()
{       
    if (crash && slowSpeed > 0) {
        rb.velocity = new Vector3 (--slowSpeed, 0, 0);
        Invoke ("Restart", respawnTimer);
    }
}

public void Restart ()
{
    Application.LoadLevel ("scene_01");
}
}

标签: c#unity3dinputtouchtouchscreen

解决方案


当您按住时,您会注意到它会在您触摸屏幕的每一帧左右交换。考虑使用TouchPhase更精细的输入。试试这个:

...
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began) {
    if(right) {
        rb.velocity = new Vector3 (rb.velocity.x, yspeed, 0);
        left = true;
        right = false;
    } else if (left) {
        rb.velocity = new Vector3 (rb.velocity.x, -yspeed, 0);
        right = true;
        left = false;
    }
}
...

查看 Android 设备上部署的代码:

在此处输入图像描述


推荐阅读