2016-12-24 227 views
1

我創建了這段代碼,但它不起作用,我不明白爲什麼。在Debug.Log中,一切似乎都很好,但while循環永遠都是真的。有沒有更好的方法將遊戲對象左右旋轉90度?如何在Y軸上向左或向右旋轉90度?

https://www.youtube.com/watch?v=7skGYYDrVQY

//Public 
public float rotateSpeed = 150f; 
public bool isMoving = false; 

//Private 
private Rigidbody myRigidbody; 


void Start() { 

    myRigidbody = GetComponent<Rigidbody>(); 
} 

void Update() { 

    Quaternion originalRotation = this.transform.rotation; 

    if (!isMoving) { 


     if (Input.GetButtonDown ("PlayerRotateRight")) { 

      //Rotate Right 
      StartCoroutine (PlayerRotateRight (originalRotation)); 

     } else if (Input.GetButtonDown ("PlayerRotateLeft")) { 

      //Rotate Left 
      StartCoroutine (PlayerRotateLeft (originalRotation)); 
     } 
    } 

} 

IEnumerator PlayerRotateRight(Quaternion originalRotation) { 

    Quaternion targetRotation = originalRotation; 
    targetRotation *= Quaternion.AngleAxis (90, Vector3.up); 

    while (this.transform.rotation.y != targetRotation.y) { 

     Debug.Log ("Current: " + this.transform.rotation.y); 
     Debug.Log ("Target: " + targetRotation.y); 

     isMoving = true; 
     transform.rotation = Quaternion.RotateTowards (transform.rotation, targetRotation, rotateSpeed * Time.deltaTime); 
     yield return null; 
    } 

    isMoving = false; 
} 

IEnumerator PlayerRotateLeft(Quaternion originalRotation) { 

    Quaternion targetRotation = originalRotation; 
    targetRotation *= Quaternion.AngleAxis (90, Vector3.down); 

    while (this.transform.rotation.y != targetRotation.y) { 

     Debug.Log ("Current: " + this.transform.rotation.y); 
     Debug.Log ("Target: " + targetRotation.y); 

     isMoving = true; 
     transform.rotation = Quaternion.RotateTowards (transform.rotation, targetRotation, rotateSpeed * Time.deltaTime); 
     yield return null; 
    } 

    isMoving = false; 
} 

回答

0

你在比較四元數而不是歐拉角。而且,由於您正在比較兩個float s,所以最好有一個閾值。

只要改變

while (this.transform.rotation.y != targetRotation.y)

while (this.transform.eulerAngles.y != targetRotation.eulerAngles.y)

while (Mathf.Abs(this.transform.eulerAngles.y - targetRotation.eulerAngles.y) > THRESHOLD)

其中THRESHOLD是騙子足夠小。爲了防止旋轉錯誤,在循環之後還要將旋轉角度設置爲精確的角度。

+1

它可以工作,但它們不是完美的90度旋轉,如果你像50次旋轉一樣旋轉,你將以5度而不是0度結束。我試圖找到一種方法來將旋轉設置在現在完美的90度外。 – jikaviri

+0

非常感謝你,我過去幾天試圖找到這個。第二種方法工作正常,我不需要使用此方法將旋轉設置爲精確的角度。 – jikaviri

1
if (Input.GetKeyDown (KeyCode.A)) { 
     transform.Rotate (0, -90, 0, Space.World); 


    }else if(Input.GetKeyDown(KeyCode.D)){ 
     transform.Rotate(0,90,0, Space.World); 
    } 

根據你的說法,因爲這簡單的東西應該工作完全正常。你選擇做這個複雜的任何特定原因?在這種情況下,我可以修改答案以適合您的代碼。

+0

使用這種簡單的方法,它立即旋轉我想慢慢旋轉,如視頻中顯示,再加上我想禁用任何其他運動,同時緩慢旋轉使用isMoving = true; – jikaviri

相關問題