- Home /
Quaternion.Lerp finishing before "t" parameter hits 1
The Problem:
I wish to rotate a cube to 180 degrees from 0 degrees. Although this is being completed, I do not have any way to track this because the "t" parameter (lerpTime) is only 0.3-0.5 instead of 1 when the rotation is 180.
To break this down more simply, "Test" is being debugged to my console way after the rotation is completed.
The Code:
Rigidbody rbdy = null;
IEnumerator RotateTest(bool reset)
{
float speed = 2f;
Quaternion oldRot = rbdy.rotation;
Quaternion newRot = rbdy.rotation * Quaternion.Euler(180, 0, 0);
float lerpTime = 0;
while (lerpTime < 1)
{
yield return new WaitForSeconds(Time.fixedDeltaTime);
Quaternion nextRot = Quaternion.Lerp(rbdy.rotation, newRot, lerpTime);
lerpTime += Time.fixedDeltaTime * speed;
rbdy.MoveRotation(nextRot);
Debug.Log(lerpTime);
}
rbdy.rotation = newRot;
Debug.LogWarning("Test");
yield break;
}
Further
I have tried setting the "newRot" value to just the Quaternion.Euler(180,0,0) without multiplying the object's rotation with the same exact result.
This rotation is incredibly quick (compared to similar Vector3.Lerps I have implemented). At a speed of 1 it takes maybe a second for the rotation to complete.
Question
How do I properly rotate an object using Quaternion.Lerp and properly track when the rotation ended?
"This rotation is incredibly quick (compared to similar Vector3.Lerps I have implemented). At a speed of 1 it takes maybe a second for the rotation to complete."
At a speed of 1, it should take exactly one second to complete. Because you're doing this:
lerpTime += Time.fixedDeltaTime * speed;
If you want it to take longer, reduce speed.
Thanks for the comment.
At a speed less than 1 (around 0.5) the rotation finishes over a longer period of time as expected, but the "t" parameter is then 0.1 or 0.2 when the rotation finishes. For instance, it takes about 2 or 3 seconds to finish the rotation with a speed of 0.5, but even after the rotation ends it takes another 15 or so seconds to be marked as complete.
To be honest, I'm not entirely sure why you're using
yield return new WaitForSeconds(Time.fixedDeltaTime);
at all. Why not simply use:
yield return null;
?
I am using Time.fixedDeltaTime because I am moving a rigidbody inside of a coroutine, so it should be close to (if not exactly) on-par with FixedUpdate().
In any event, I tried both yield return null and Time.deltaTime ins$$anonymous$$d with the same result at a speed of 0.5F. I updated the lerpTime to use Time.deltaTime ins$$anonymous$$d of FixedDeltaTime as well.
Image may clarify something that I couldn't with words alone.
*Edited for clarity
fixedDeltaTime is just a float, has nothing to do with FixedUpdate. You want to yield until WaitForFixedUpdate.