I’m trying to rotate a cube by 90 degrees on a button press, over a period of a few seconds. I pieced togethor a bit of code from various answers on here, and it seems to work alright.
Except, it never rests perfectly on zero degrees. It always goes to exactly 270 degrees, usually to exactly 90 and 180, but never to exactly 0 (i’ve seen it anywhere from -8 to 6!) Surely there must be a way with this code to animate it going exactly 90 degrees every button press, with no offset?
using UnityEngine;
using System.Collections;
public class Cube2 : MonoBehaviour {
public float DegreesPerSecond = 180f; // degrees per second
private Vector3 currentRot, targetRot;
private bool rotating = false;
// Use this for initialization
void Start () {
currentRot = transform.eulerAngles;
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("RotateCube") ) {
StartCoroutine(Rotate());
}
}
IEnumerator Rotate(){
if (!rotating) {
rotating = true; // set the flag
targetRot.y = currentRot.y + 90; // calculate the new angle
while (currentRot.y < targetRot.y){
currentRot.y = Mathf.MoveTowardsAngle(currentRot.y, targetRot.y, DegreesPerSecond * Time.deltaTime);
transform.eulerAngles = currentRot;
yield return null;
}
rotating = false;
}
}
}
I tried setting the “while” condition to currentRot.y <= targetRot.y, but that broke it after 1 button press. You would think there would be an easy way to animate a rotation of 90 degrees on a button press, evidently not though!!