简体   繁体   中英

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?

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;

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 at value outside of [0, 1], ie. an extrapolate attempt, would be clamped to the valid range.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM