- Home /
Why is my Lerp returning NaN?
I have a speedometer in my UI and am using a mask over an image to show the player's speed.
So half speed looks like this:
And full speed looks like this:
The gameplay means that there can be sudden bursts of acceleration/deceleration and when this happens, the amount of the bar that is filled jumps up and down instantly. To make this look a bit nicer I tried to Lerp between the values but it returns a NaN.
// Works Correctly
speedoPowerbar.fillAmount = ((player.rb.velocity.magnitude / player.speeds[player.speedIndex]) / 4) * player.speedIndex;
// Returns a NaN
float speedoTarget = ((player.rb.velocity.magnitude / player.speeds[player.speedIndex]) / 4) * player.speedIndex;
speedoPowerbar.fillAmount = Mathf.Lerp(speedoPowerbar.fillAmount, speedoTarget, Time.deltaTime);
Answer by glasshalfpool · May 20, 2021 at 09:38 AM
I fixed this by changing the Lerp to SmoothDamp:
float speedoTarget = ((player.rb.velocity.magnitude / player.speeds[player.speedIndex]) / 4) * player.speedIndex;
speedoPowerbar.fillAmount = Mathf.SmoothDamp(speedoPowerbar.fillAmount, speedoTarget, ref speedoVelocity, 1f);
Answer by Bunny83 · May 20, 2021 at 09:40 AM
Any math equation will return NaN if any of the used operands is a NaN value. There are only a few operations that can actually produce NaN values. In your case it's most likely the operation x/y
where x and y are both 0
.
Your issue is once you have a NaN value, you won't get rid of it since the way you use Lerp incoperates the old fillAmount value. So once it's NaN, even "speedoTarget" has a valid value, the result will still be NaN since lerping from NaN to a valid value will still produce NaN.
So you should generally avoid such calculations that can produce NaNs or at least check the operands before carrying out the calculation. It's generally not recommended to just check for NaN values afterwards since a NaN value generally means you have an issue in your logic that should be fixed.
Thanks for the insight. I'll bear that in $$anonymous$$d.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Scale Object Using Lerp? 2 Answers
Flip over an object (smooth transition) 3 Answers