- Home /
Slerp Finishes Rotation When Progress is 0.5f
Hi,
I have a question about using Slerp method. I'm using it to rotate an object so that it will be looking at a point. However as far as I know, when progress is 1, Slerp will be done. But in my case it turns towards the point I want when progress is 0.5f. And If I continue turning until progress is 1, it turns back to its original rotation.
Actually my code is working in that way but I wonder why it doesn't work as it should when slerp is called until progress is 1. Thanks in advance!
private IEnumerator TurnTowardsFinalTrack_CO()
{
float progress = 0f;
Transform centerP = selectedRunway.GetRunwayCenterPoint();
Vector3 dirVector = -centerP.position + transform.position;
Quaternion targetRotation = Quaternion.LookRotation(dirVector, Vector3.forward);
Vector3 correctionVector = Vector3.zero;
while (progress < 0.5f) //weirdly works in that way
{
transform.transform.rotation = Quaternion.Slerp(transform.transform.rotation, targetRotation, progress);
correctionVector.z = transform.transform.eulerAngles.z;
transform.eulerAngles = correctionVector;
progress += Time.deltaTime;
yield return null;
}
}
Answer by KoenigX3 · May 25, 2020 at 02:48 PM
Quaternion.Slerp and other interpolating functions usually need 3 parameters:
A starting rotation (or position, if its a Vector3 interpolation)
The desired rotation (or position)
A float between 0 and 1.
Normally, the first and second parameter does not change. In your case, your starting rotation is not static, because it will always be the current rotation. As you interpolate, transform.rotation changes, and you interpolate with the new rotation as the starting point.
Store the starting rotation in a Quaternion before the interpolation, and use it as your first parameter.
Quaternion startRotation = transform.rotation;
while(progress <= 1)
{
transform.rotation = Quaternion.Slerp(startRotation, targetRotation, progress);
}
As a side note: using transform.rotation as your first parameter is not always a problem. You can create a decreasing interpolation with that. The rotation is actually changing between 0.5 and 1, but the change is so subtle, it is usually unnoticed.
Another side note: you don't have to use transform.transform, you can replace it with transform.
I missed that startRotation part, now I see where my thinking was faulty. And about transform.transform thing, oh god.. It is totally my unintentional writing. How come I didn't realize it, shameful considering the number of times I checked that code :) Anyway, thanks for the clear answer!