0

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?

Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
Martin Dawson
  • 7,455
  • 6
  • 49
  • 92

3 Answers3

6

I think you're using Lerp bad.

As written in Unity Documentation (http://docs.unity3d.com/ScriptReference/Mathf.Lerp.html), you should pass 3 floats, the minimum as first argument, the maximum as second and the time as third.

This third should be beetwen 0 and 1.

Aside from that, you can always make the number negative after lerping it.

Some examples :

  • In case you want from -10 to 10, lerp from 0 to 20 and then substract 10.

    float whatever = Mathf.Lerp(0f, 20f, t);

    whatever -= 10f;

  • In case you want from 0 to -50, lerp from 0 to 50 and then make it negative.

    float whatever = Mathf.Lerp(0f, 50f, t);

    whatever = -whatever;

Snak
  • 673
  • 1
  • 5
  • 19
2

Well, you cannot actually.

A psuedo-codish implementation of a Lerp function would look like this:

float Lerp(float begin, float end, float t)
{
    t = Mathf.Clamp(t, 0, 1);
    return begin * (1 - t) + end * t;
}

Therefore, any attempt to give a t value outside of [0, 1], ie. an extrapolate attempt, would be clamped to the valid range.

Fatih BAKIR
  • 4,569
  • 1
  • 21
  • 27
2

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.

Robert Rouhani
  • 14,512
  • 6
  • 44
  • 59