c# - 触摸屏,如何调整我的代码以仅对一根手指做出反应
问题描述
我正在尝试为我的安卓手机游戏添加有限的触摸屏控件。我一直在看所有这些教程,但我只是没有得到简单的部分之一,至少我认为它很简单。在我的手机上,当你用手指点击它时,我有一辆向左行驶的卡车。当我再次点击它时,我希望它正确。每次点击屏幕时,它都应该朝另一个方向移动,左右交替。它现在很有效,但不是真的。当你第一次点击它时,它会向左移动。但是为了让它正确,你必须用一根手指按住屏幕,然后用第二根手指触摸它。我只想让它一次只对一根手指做出反应,这样你就可以用一只手弹奏它。所以这是我的代码。我究竟做错了什么?我如何解决它?谢谢大家。
试图摆脱回报。尝试根据其他教程调整现有代码并在其中添加其他内容。
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");
}
}
解决方案
当您按住时,您会注意到它会在您触摸屏幕的每一帧左右交换。考虑使用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 设备上部署的代码:
推荐阅读
- python - 获取类方法引用到 dict
- laravel - 如何使用 laravel 中的一个函数在同一个文件中加载两个不同的视图
- python - 如何使用具有多个处理程序的 Python 日志记录模块将一条日志记录发送到文件,并将另一条日志记录发送到电子邮件
- python-3.x - 不确定tic_tac_toe换板
- java - 使用 Java 批量上传到 Box*
- javascript - 如何使用 JS 和 DOM 创建元素、设置属性、使用 innerHTML 和 appendChild
- c# - 如何从方法返回一些东西以打破 C# 中的循环?
- javascript - req.isAuthenticated() 重定向更改?
- azure - Azure“文本转语音”返回“无效的 CID 或语言”。这是什么意思?
- dictionary - 如何链接 LinkedList 节点以映射值