【发布时间】: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