Calculate NavMeshAgent speed without NavMeshAgent component

Is there any way to calculate the speed of a NavMeshAgent without having that component attached? I’m asking because I move my NPC’s only on the server application. The client doesn’t have any information about the navmesh and I would like to avoid syncing the speed variable over the network.

You could calculate the speed from the transform component’s position. Save the position each frame and compare it with the position in the frame before.

1 Like

why?

“could” but all that extra re-calc for everything that needs to know rather than exposing the actual speed variable from the authoritative source feels a little off :slight_smile:

Already tried that, but calculating it this way it doesn’t seem to match the navmeshagent velocity.

The game I work on allows pretty much NPC’s onscreen (50+). So it would be better to safe bandwidth for values which change often.

What do you need the speed for?

If it’s for animation, base the animation on the measured speed (transform position change over time) rather than the agent’s velocity. Then you don’t need to know the speed.

The fastest way to send information is to not send it!

Like this one?

Vector3 velocity = (lastPosition - transform.position) / Time.deltaTime;
lastPosition = transform.position;

Pretty much, but that might jitter. If that happens, try smoothing it out:

Vector3 velocity = (lastPosition - transform.position) / Time.deltaTime;
lastPosition = transform.position;

currentVelocity = Mathf.MoveTowards(currentVelocity, velocity, Time.deltaTime * smoothSpeed);

Where you find smoothSpeed based on testing.

1 Like

One thing, if you want your velocity vector to face the correct direction, it would be transform.position - lastPosition. If you only need the magnitude, then it doesn’t matter.

2 Likes