我创建了这段代码,但它不起作用,我不明白为什么。在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