c# - 通过触摸按钮或图像而不是 A - D 键在表面上左右移动 3d 块
问题描述
我在 YouTube 教程的帮助下制作了一个小游戏,但遇到了问题。电脑上的游戏一切正常,我使用 A 和 D 向左或向右移动立方体以避开前面的障碍物。Block 有一个前进速度,可以以给定的速度自行向前移动。
但我想在我的 Android 手机上测试我的游戏,所以我必须使用触摸屏按钮或触摸手机屏幕的左侧或右侧来控制对象。使用 An 或 D 键很容易,但使用移动触摸......并非如此。下面是我现在用于移动和图片的代码。
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 2000f; // Variable that determines the forward force
public float sidewaysForce = 500f; // Variable that determines the sideways force
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) // If the player is pressing the "a" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
解决方案
它一点也不难。首先将运动提取到单独的方法中
public void MoveRight()
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
public void MoveLeft()
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
MoveRight();
if (Input.GetKey("a")) // If the player is pressing the "a" key
MoveLeft();
}
剩下要做的就是将您的按钮绑定到编辑器中的这些方法
推荐阅读
- reactjs - 为什么我从 laravel API 收到空对象?
- sqlite - SQLite 工具可以在表中的现有条目之间插入条目
- python - 打印 1 个列表而不是多个列表
- python - 当我在 pyqt5 中按 Enter 时转到下一个 LineEdit
- flutter - gridview.count 在颤动中给出范围错误
- c++ - 将矩阵中的向量相加,在 C++ 中逐个元素地求和
- javascript - Svelte 给我“未捕获的 ReferenceError:未定义要求”
- signalr - Azure Signal R 服务 (ASRS) 增值
- elasticsearch - Elasticsearch 嵌套查询未按预期工作
- c - 为什么我的代码在 codeBlocks 中输出正确,但在 HackerRank 中输出错误?