Whenever you want something moving within a specified time I would recommend to not do it in Update
but instead use a Coroutine.
It works like a little temporary Update
method and is executed each frame until the next yield
. this is better to maintain and control than the Update
method.
Then do your rotation using Quaternion.Lerp
or also Quaternion.Slerp
depending a bit on your needs
private IEnumerator RotateOverTime(Transform transformToRotate, Quaternion targetRotation, float duration)
{
var startRotation = transformToRotate.rotation;
var timePassed = 0f;
while(timePassed < duration)
{
var factor = timePassed / duration;
// optional add ease-in and -out
//factor = Mathf.SmoothStep(0, 1, factor);
transformToRotate.rotation = Quaternion.Lerp(startRotation, targetRotation, factor);
// or
//transformToRotate.rotation = Quaternion.Slerp(startRotation, targetRotation, factor);
// increae by the time passed since last frame
timePassed += time.deltaTime;
// important! This tells Unity to interrupt here, render this frame
// and continue from here in the next frame
yield return null;
}
// to be sure to end with exact values set the target rotation fix when done
transformToRotate.rotation = targetRotation;
}
Now in order to start this routine you would call it via StartCoroutine
like e.g.
// simply stop any other running routine so you don't get concurrent ones
StopAllCoroutines();
StartCoroutine(transformToRotate, otherTransform.rotation, 3f);