How to Rotate on Y Axis by 90 degrees left or right?
I created this code but it doesn't work and i don't understand why. In the Debug.Log
everything seems fine but the while loops are true for ever. Is there a better way to Rotate the gameobject by 90 degrees left and right?
https://www.youtube.com/watch?v=7skGYYDrVQY
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//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;
}
}
This raises a few questions : - why use a Coroutine if not using a yield statement other than return null ? - why not use transform.Rotate () method ?
Answer by AurimasBlazulionis · Dec 24, 2016 at 09:18 PM
The simplest way to rotate by 90 degrees (in world axis) is to do the following transform.rotation *= Quaternion.Euler(0, 90f * rotateSpeed * Time.deltaTime, 0)
.
The quaternions will not be the same since they are using floating points and that is their nature. You need to use something like Quaternion.Angle to check if they are "close enough".
There are a lot of ways to rotate the gameobject but what code should i put in the while loop to make this work? I tried a lot of ways but i didnt find a way to make this work if i rotate 100 times right or left for example. I only managed to make this work with 3 rotates then it broke.