Search code examples
c#unity-game-enginelerp

Unity3D C# Negative Lerp?


I am wanting to lerp the variable that controls my animations speed so it transitions fluidly in the blend tree.

 void Idle()
     {
         _agent.SetDestination(transform.position);
             //Something like the following line
         _speed = Mathf.Lerp(0.0f, _speed, -0.01f);
         _animationController._anim.SetFloat("Speed", _speed);
     }

I'v read that you can't lerp negatives, so how do I do this?


Solution

  • The t value in a lerp function between a and b typically needs to be in the 0-1 range. When t is 0, the function returns a and when t is 1, the function returns b. All the values of t in between will return a value between a and b as a linear function. This is a simplified one-dimensional lerp:

    return a + (b - a) * t;
    

    In this context, negative values of t don't make sense. For example, if your speed variable is 4.0f, the result of lerp(0, 4, -0.01f) would be:

    0 + (4 - 0) * -0.01
    

    which returns -0.04.

    The simplest way to solve this issue is to simply flip a and b instead of trying to use a negative t.

    _speed = Mathf.Lerp(_speed, 0.0f, 0.01f);
    

    Another suggestion would be to use Mathf.SmoothStep and store the original speed instead of applying the function on the constantly changing _speed to get a really smooth transition.