How do I find an accurate current speed of a navmesh agent?

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?

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);
}

• Ok well that's definitely better but it still fluctuates a small amount... – mr-matt Nov 22 '16 at 17:16

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);
}