0
\$\begingroup\$

So I have a blendtree of an idle/walk/run animation of a character (the navmesh agent). I want to use a normalised float of the speed of the navmesh agent to control the blend of the animation cycles. Currently I use this:

void FixedUpdate ()
{
    speed = (transform.position - lastPosition).magnitude;
    lastPosition = transform.position;

    print(speed); 
}

However the result is fluctuating all over the place and the animations blends look crap. How do I find a more accurate speed of the navmesh agent?

\$\endgroup\$
1
\$\begingroup\$

You are doing it right way, the problem is that on navmesh object can change its speed rapidly. You should interpolate object speed in order to get rid of rapid changes. Just update your method like this:

void FixedUpdate()
{
    speed = Mathf.Lerp(speed, (transform.position - lastPosition).magnitude, 0.7f /*adjust this number in order to make interpolation quicker or slower*/);
    lastPosition = transform.position;

    print(speed);
}
\$\endgroup\$
  • \$\begingroup\$ Ok well that's definitely better but it still fluctuates a small amount... \$\endgroup\$ – mr-matt Nov 22 '16 at 17:16
0
\$\begingroup\$

It seems that the thing I needed was to divide the speed by Time.deltaTime.

This is what works now:

void FixedUpdate()
{
    speed = Mathf.Lerp(speed, (transform.position - lastPosition).magnitude / Time.deltaTime, 0.75f);
    lastPosition = transform.position;

    print(speed);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.