如何在Y轴上向左或向右旋转90度?

时间:2016-12-24 21:01:57

标签: c# unity3d rotation transform

我创建了这段代码,但它不起作用,我不明白为什么。在Debug.Log中,一切似乎都很好但是while循环永远都是真的。有没有更好的方法将游戏对象向左和向右旋转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;
 }

2 个答案:

答案 0 :(得分: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);
    }

根据你的说法,这样简单的东西应该可以完美地运作。你选择这么复杂的任何特殊原因?在这种情况下,我可以修改答案以适合您的代码。

答案 1 :(得分:0)

您正在比较四元数而不是欧拉角。而且,由于您要比较两个float,所以最好有一个阈值。

只需更改

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是一个足够小的常数。还要在循环后将旋转设置为其精确角度,以防止旋转错误。