首页 > 解决方案 > 通过触摸按钮或图像而不是 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();
        }
    }
}

在此处输入图像描述

标签: c#unity3d

解决方案


它一点也不难。首先将运动提取到单独的方法中

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();
}

剩下要做的就是将您的按钮绑定到编辑器中的这些方法


推荐阅读