NPC to travel to destination while avoiding obstacles
The introduction of Unity’s NavMeshAgent has greatly simplified the coding for Non-Player Character (NPC) and enemy agent behaviors. In this recipe, we’ll add some wall obstacles (scaled cubes) and a NavMeshSurface so that Unity knows not to try to walk through walls.
We’ll then add a NavMeshAgent component to our NPC GameObject and tell it to head to a stated destination location by intelligently planning and following a path while avoiding the wall obstacles.
When the NavMeshSurface is added, the Scene panel displays the blue-shaded walkable areas, as well as unshaded, non-walkable areas at the edge of the terrain and around each of the two wall objects:
Figure 12.1: Example of an NPC avoiding obstacles
Getting ready
The required SandAlbedo
texture terrain can be found in the 12_01
folder.
You will also need to install the AI Navigation package, but first, make sure you are signed...