Hi there!
I have a question related to NavMeshAgents and moving destinations.
To illustrate with an example, you may want an Enemy object approach the Player object, while the player is moving. How do you do that efficiently with a NavMeshAgent?
I ask, because I know that calculating the path (either through SetDestination () or CalculatePath () ) is costly, but what if the target is moving, you have to recalculate.
The only solution I could think of so far was to periodically, but not in every frame, call SetDestination (), possibly even checking if the target moved.
I was thinking that maybe it is possible to use a previously calculated path to modify the endpoint, but I haven’t seen any API element for this (and I also realise it would be difficult to implement this).
Is there a better and/or more efficient solution to approach a moving destination?
No, not that I know of, but it sounds like you’re on the right track. I would check it periodically, maybe every second or two, and definitely track if they have moved. Maybe make it conditional such as (time>2 && dist>1) so both have to be met. Then, make sure you take over the pathfinding yourself when they get close so there isn’t a noticeable jitter.
This is the coroutine I came up with:
private IEnumerator FollowTarget(float range, Transform target) {
Vector3 previousTargetPosition = new Vector3(float.PositiveInfinity, float.PositiveInfinity);
while (Vector3.SqrMagnitude(transform.position - target.position) > 0.1f) {
// did target move more than at least a minimum amount since last destination set?
if (Vector3.SqrMagnitude (previousTargetPosition - target.position) > 0.1f) {
navMeshAgent.SetDestination (target.position);
previousTargetPosition = target.position;
}
yield return new WaitForSeconds (0.1f);
}
yield return null;
}