- Home /
Coroutine Rotation Drifting/Imprecise
My script handling a 360-degree rotation over time on the Z-axis keeps drifting by about +/-2 degrees when complete, and I cannot figure out why this is happening. I have disabled all other of my movement/rotation scripts as I at first thought they were interfering but it didn't seem to fix the problem. Here's my script:
public float rollDuration = 1.0f;
private bool inRoll = false;
void Update ()
{
if(!inRoll)
{
if(Input.GetButtonDown ("RollLeft"))
{
StartCoroutine("Roll", -1);
}
else if(Input.GetButtonDown ("RollRight"))
{
StartCoroutine("Roll", 1);
}
}
}
IEnumerator Roll(int direction)
{
inRoll = true;
float time = 0.0f;
Vector3 initialRotation = transform.localRotation.eulerAngles;
Vector3 currentRotation = initialRotation;
Vector3 targetRotation = new Vector3(currentRotation.x, currentRotation.y, currentRotation.z - (360.0f * direction));
while(time < rollDuration)
{
currentRotation.z = Mathf.Lerp(initialRotation.z, targetRotation.z, time/rollDuration);
transform.localRotation = Quaternion.Euler (currentRotation);
time += Time.deltaTime;
yield return null;
}
inRoll = false;
}
Any insight or help on this issue is greatly appreciated! :)
Answer by GameVortex · Jan 11, 2015 at 07:51 PM
You only rotate while time is less than rollDuration, so your roll will not get preciesly to the target rotation because you will never supply the Lerp function with the value higher or equal to 1. You need to do one more roll/lerp calculation the first frame that time >= rollDuration in order to get currentRotation to be equal to targetRotation.
The easiest way would actually be to set currentRotation to be equal to targetrotation after the while loop.
while(time < rollDuration)
{
currentRotation.z = Mathf.Lerp(initialRotation.z, targetRotation.z, time/rollDuration);
transform.localRotation = Quaternion.Euler (currentRotation);
time += Time.deltaTime;
yield return null;
}
transform.localRotation = Quaternion.Euler (targetRotation);
Thank you very much for not only providing the solution, but a clear explanation as well! This solution worked absolutely perfectly :)
Cheers!