2017-06-02 69 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

工作很好。擺脫了不必要的代碼,非常感謝! –