- Home /
How to lerp with a changing "from" value?
It's possible I'm not even using this right but basically I'm making a hunger system and I'm calling this in fixed update:
public void Starve()
{
if(CurrentHunger > 0)
{
CurrentHunger = Mathf.Lerp(CurrentHunger, 0, HungerRate * Time.deltaTime);
}
}
In this example, CurrentHunger starts as 100. Hunger rate is 15. My time.deltaTime is 0.02. With this use of lerp, basically, my from value is always changing.
So:
1 second it is 70
2 seconds it is 49
3 seconds it is 34.3
4 seconds its is 24.01
See? It's not decrementing linearly. Am I even using lerp right? And what do I need to do to fix this?
Answer by Bunny83 · Jul 21, 2016 at 11:52 PM
Lerp won't work in that case. Both values need to be constant.
Instead of Lerp you might want to use Mathf.MoveTowards which does exactly what you want.
Lerp is implemented like this:
public static float Lerp(float a, float b, float t)
{
return a + (b - a) * Mathf.Clamp01(t);
}
while MoveTowards is implemented like this:
public static float MoveTowards(float current, float target, float maxDelta)
{
if (Mathf.Abs(target - current) <= maxDelta)
{
return target;
}
return current + Mathf.Sign(target - current) * maxDelta;
}
I also think I have found a solution:
I already had a value called $$anonymous$$axHunger which is 100;
I made a new value called currentHungerDelay. This will help update the third parameter in the lerp section as I need to keep the values of the first two parameters constant, like you said.
Therefore, I set currenthunger equal to the new lerp value and I made sure current hunger was not part of the parameters in there. Here's the code
public void Starve()
{
currentHungerDelay += Time.deltaTime;
if (currentHungerDelay >= HungerRate)
currentHungerDelay = HungerRate;
float t = currentHungerDelay / HungerRate;
CurrentHunger = $$anonymous$$athf.Lerp($$anonymous$$axHunger, 0, t);
}
Your answer
Follow this Question
Related Questions
Get positions at equal intervals between two Vector3 3 Answers
Are there any easing functions built into Unity 5? 1 Answer
Linear optimization 0 Answers
How can I follow the terrain 1 Answer