【问题标题】:Moving a 3d block on a surface left and right by touch button or image instead of A - D Keys通过触摸按钮或图像而不是 A - D 键在表面上左右移动 3d 块
【发布时间】:2019-04-17 02:47:37
【问题描述】:

我在 YouTube 教程的帮助下制作了一个小游戏,但遇到了问题。 电脑上的游戏一切正常,我使用 A 和 D 向左或向右移动一个立方体以避开前面的障碍物。 方块有一个前进速度,可以以给定的速度自行向前移动。

但我想在我的 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


    【解决方案1】:

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

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

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

    【讨论】:

    • 完美,几周后就完美了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    相关资源
    最近更新 更多