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\$

2 Answers 2

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\$
1
  • \$\begingroup\$ Ok well that's definitely better but it still fluctuates a small amount... \$\endgroup\$
    – mr-matt
    Commented Nov 22, 2016 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\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .