2017-06-02 51 views
0

使用UI画布按钮,我试图用指针向左和向右移动对象,并且在指针向上移动应该停止。然而,只有开关箱向右移动,并且我的物体不会向左移动(但会打印报表)统一游戏触摸按钮 - 对象只向右移动,而不是向左移动

此代码附加到左侧按钮。在指针向下调用MoveLeft()时,在指针向上调用NoLeft()(通过使用事件触发器的检查器)。 boolean 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,它们相互镜像。

在此先感谢您的帮助。

回答

1

你太过于复杂了,这就是它出错的地方。只需要一个方法,该方法需要一个正值或负值的浮点值。在你的情况下,isLeft和isRight总是对或错。所以FixedUpdate运行,它将运行两个开关并打印匹配状态。

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

移动是分配给两个按钮,然后得到的极性(1或-1),以检验员的方法。

+0

工作很好。摆脱了不必要的代码,非常感谢! –