// Rotate the object from it's current rotation to "newRotation" over "duration" seconds
void StartRotate(Vector3 newRotation, float duration = 0.5f)
{
if (SlerpRotation != null) // if the rotate coroutine is currently running, so let's stop it and begin rotating to the new rotation.
StopCoroutine(SlerpRotation);
SlerpRotation = Rotate(newRotation, duration);
StartCoroutine(SlerpRotation);
}
IEnumerator SlerpRotation = null;
bool done = false;
IEnumerator Rotate(Vector3 newRotation, float duration)
{
Quaternion startRotation = transform.rotation; // You need to cache the current rotation so that you aren't slerping from the updated rotation each time
Quaternion endRotation = Quaternion.Euler(newRotation);
for (float elapsed = 0f; elapsed < duration; elapsed += Time.deltaTime)
{
float t = elapsed / duration; // This is the normalized time. It will move from 0 to 1 over the duration of the loop.
transform.rotation = Quaternion.Slerp(startRotation, endRotation, t);
yield return null;
}
done = false;
transform.rotation = endRotation; // finally, set the rotation to the end rotation
SlerpRotation = null; // Clear out the IEnumerator variable so we can tell that the coroutine has ended.
}