【问题标题】:Unity game touch button - object only moves right, not leftUnity 游戏触摸按钮 - 对象只向右移动,不向左移动
【发布时间】:2017-06-02 16:39:52
【问题描述】:

使用 UI 画布按钮,我试图在指针向下的情况下左右移动我的对象,在指针向上时,移动应该停止。然而,只有向右移动的 switch case 执行,并且我的对象不会向左移动(但是它会打印语句)

此代码附在左侧按钮上。在指针向下时调用 MoveLeft(),在指针向上时调用 NoLeft()(通过使用事件触发器的检查器)。布尔值 isLeft 控制是否向左移动。

public class LeftButton : MonoBehaviour {

public GameObject playerC;

public void MoveLeft(){
    Debug.Log ("Moving left");
    playerC.GetComponent<PlayerController>().isLeft = true;

}

public void NoLeft(){
    Debug.Log ("Not moving left");
    playerC.GetComponent<PlayerController> ().isLeft = false;
}
}

下面的代码附在播放器上,这是我怀疑的问题所在,我只能向右移动。然而,isLeft 的日志语句将打印出来。

public class PlayerController : MonoBehaviour {

private Rigidbody playerRigidBody;
[SerializeField]
public float movementSpeed;

public bool isLeft;
public bool isRight;


void Start () {

    playerRigidBody = GetComponent<Rigidbody> ();
}

void FixedUpdate () {

    switch (isLeft) {
    case true:

        print ("Move left is true");
        playerRigidBody.MovePosition(transform.position + transform.forward * 0.5f);
        break;

    case false:

        print ("No longer left");
        playerRigidBody.MovePosition (transform.position + transform.forward * 0f);
        break;

    }

    switch (isRight) {
    case true:

        print ("Move right is true");
        playerRigidBody.MovePosition (transform.position - transform.forward * 0.5f);
        break;

    case false:

        print ("No longer right");
        playerRigidBody.MovePosition (transform.position - transform.forward * 0);
        break;

    }

}

即使我从未触摸并释放右键,“不再正确”的语句也会打印出来。

如果您想知道 UI 由两个按钮组成,左和右。它们都有自己的脚本 LeftButton(上图)和 RightButton,它们只是相互镜像。

提前感谢您的帮助。

【问题讨论】:

    标签: unity3d input touch transform


    【解决方案1】:

    你把它复杂化了,这就是它出错的地方。只需有一个采用浮点值的方法,该浮点值可以是正数或负数。在您的情况下, isLeft 和 isRight 始终为真或假。所以 FixedUpdate 运行时,它会同时运行 switch 并打印匹配的状态。

    public class PlayerController : MonoBehaviour 
    {
        public void Move(float polarity) {
            playerRigidBody.MovePosition(transform.position + transform.forward * polarity);
        }
    }
    

    Move 是您分配给两个按钮的方法,然后将极性(1 或 -1)分配给检查器。

    【讨论】:

    • 效果很好。摆脱了不必要的代码,非常感谢!