Efficient way to handle navigation with NavigationAgent2D?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By zexanima

Currently I’m spawning enemies and just moving them straight towards the player. I want to incorporate some pathfinding so they avoid obstacles. I’ve got the NavigationAgent2D to work but the issues is updating it. Every time the player moves a new path will need to be calculated and that operation, to no surprise, seems to be slow. Specially when there are multiple enemies.

What would be a better way to handle this? Would running set_target_location in a separate thread help to avoid this or is there a more efficient way? Should I even be using pathfinding for this kind of issue?

:bust_in_silhouette: Reply From: ChePhan

If calculation the path is the actual issue try updating it not every frame.

Variant a.:
Have the player position saved and calculate the distance to that saved location. If it is above a certain threshold where it would make sense to update the enemy path emit a signal that enemies catch.

Variant b.:
Save nav_agent.get_next_location() after calculating a new path and update only when they reach it. The player can probably only move so far in this time that the next location might still be a somewhat valid movement.

Variant c.:
Use a timer. Calculate the path only every 0.5 seconds. For very intelligent enemies, decrease that time.

Pathfinding only makes sense when there are actual obstacles and walls. When you’re in mostly free space, don’t use it.