[C#] Smooth Object Rotation via Coroutines and Quaternion Lerp
Solution
Unity 2017.1.x - Unity 6.3.x
Published 13 days ago
A while loop executed inside a standard method completes entirely within a single frame. This prevents the object from showing an intermediate state, causing transform.rotation to snap instantly to the target. Standard methods block the main thread and the rendering process until they finish, rendering Time.deltaTime useless for visual smoothing in that context.
To ensure a rotation occurs over time, the execution must be yielded back to the Unity engine each frame. This is achieved by moving the logic into a Coroutine, which allows the use of yield return null to pause execution until the next frame. By tracking the elapsedTime, we can interpolate between the start and end rotations linearly.
- Cache the starting rotation using
transform.rotationbefore entering the loop. - Calculate the specific target orientation using
Quaternion.Euleror a target reference. - Initialize the elapsedTime float to zero to begin the transition tracking.
- Create a
whileloop that continues as long as elapsedTime is less than the desired duration. - Increment elapsedTime by
Time.deltaTimein every iteration to maintain time-consistency. - Update
transform.rotationusingQuaternion.Lerp, passing in the start, end, and the normalized value of elapsedTime divided by duration. - Use
yield return nullinside the loop to allow Unity to render the current frame before proceeding.
Additional Tips
- For a more polished feel, wrap the interpolation ratio in
Mathf.SmoothStep(0, 1, t)to add easing to the start and end of the rotation. - Always apply the final target rotation explicitly after the loop finishes to correct any floating-point inaccuracies accumulated during the elapsedTime calculations.
- If you need to stop an ongoing rotation before starting a new one, store the
Coroutinein a variable and callStopCoroutinebefore initiating the next sequence.
TL;DR
Distribute rotation logic across multiple frames using IEnumerator and Quaternion.Lerp to achieve frame-rate independent smoothing.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.