- Home /
Lerp returning max value halfway
Hello, well my problem seems to be quite common and yet I haven't been able to fix it... degrees and robotjoints are float values, in an array, but are simple floats.
Lerp is misbehaving, I think... the code is the next:
private IEnumerator MoveJoints(float[] degrees, float speed) {
float t = 0.0f;
while (t < 1) {
t += Time.deltaTime * speed;
for (int i = 0; i < robotJoints.Length; i++) {
robotJoints[i] = Mathf.Lerp(robotJoints[i], degrees[i], t);
}
Debug.Log("In " + t.ToString() + " the value is " + robotJoints[0].ToString() + " aiming for " + degrees[0].ToString());
yield return null;
}
done = true;
}
I can see with the debug that the value of robotjoints[0] becomes the same as degrees[0] when t is 0.5 or higher... shouldn't it be at 1?
What am I not seeing?
Answer by highpockets · Apr 16, 2019 at 10:48 AM
This is likely because you are passing the lerp function the first param as the updated float value on every iteration. You need a constant float value as the start float to do a linear interpolation. Since the interpolation is not linear with your code, you are getting the results as is. Try passing the start float that stays constant until your reach 1.0f and this will likely not happen.
Converted to an answer. Note that one may want to use $$anonymous$$athf.$$anonymous$$oveTowardsAngle or $$anonymous$$athf.$$anonymous$$oveTowards in such cases. Though if those are joint angles of a robot and they should arrive all at the target position at the same time Lerp would make more sense.
I cant believe I didn't see this! Indeed, this was the problem, thank you for your help!