我創建了這段代碼,但它不起作用,我不明白爲什麼。在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;
}
它可以工作,但它們不是完美的90度旋轉,如果你像50次旋轉一樣旋轉,你將以5度而不是0度結束。我試圖找到一種方法來將旋轉設置在現在完美的90度外。 – jikaviri
非常感謝你,我過去幾天試圖找到這個。第二種方法工作正常,我不需要使用此方法將旋轉設置爲精確的角度。 – jikaviri