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?
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;
}
}