Last active
October 8, 2017 23:41
-
-
Save jirevwe/776cc774b90a68e9a1ed35be11960476 to your computer and use it in GitHub Desktop.
Unity C# snippet to rotate a transform to a new relative rotation over a number of seconds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment