2016-12-24 222 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

相关问题