In the previous two lessons, we set up our NavMesh, added a NavMesh agent to the soldier, and wrote code to get the soldier moving across the NavMesh. In this lesson, we'll throw some obstacles in the soldier's path.
Setting Up Obstacles
The Unity AI system allows you to set up obstacles. An AI character will then negotiate the obstacles on its way to its destination. Let's see how that works.
You can either download something to use as an obstacle from the Unity Asset Store or just go with a cube. (We downloaded some crates by Amanda3D.)
Place an obstacle in the Scene in the soldier's path.
In order for Unity to see this crate as an obstacle, you can add a component called a NavMesh Obstacle.
So, with your new crate or cube obstacle selected, click the Add Component button in the Inspector. Type Nav in the search box and select NavMesh Obstacle from the list:
If you zoom in on your obstacle, you'll see a green outline around it:
The outline comes from the Shape, Center, Size and Carve values for the Nav Mesh Obstacle component in the Inspector:
You can change these. You'd want to change them to stop the soldier getting too close to the crate. He'll only get as close as the green outline. Change the values so that the green cube outline sticks out from your crate or cube:
For a cube, try changing not only the Size values but the Center Y value as well.
Every time you add to your NavMesh, you need to re-Bake it.
So, click on your Navigation tab next to the Inspector. Click the Object button at the top. In the Hierarchy, select all of your obstacles.
Now check the Navigation Static and Generate Off Mesh Links boxes. Also, click the dropdown for Navigation Area. Set your cubes or crates to Not Walkable:
Now click the Bake button at the top. Click Bake at the bottom:
If you look at your Scene, you should see that your obstacles have been baked into the NavMesh. The grey areas around the crates in the image below show where the AI character can't walk:
And that's it - no coding needed!
Play your game. You should see your soldier move around your obstacle on his way to the destination point, as in the short video below: (5 seconds)
You can add as many obstacles as you want to your Scene. Just remember to re-Bake when you're done.
We'll leave it there with this introduction to AI. There's lot's more we could do. For example, we used triggers in a previous lesson. We placed a cube over a health pack and then turned the mesh renderer off. When you get close to the cube, a script is activated and the player is able to pick up the health pack. You could do something similar with the AI. When the player passes through a trigger, the soldiers will start to run, otherwise, they can be just standing around.
If you wanted an enemy to follow the player, a zombie enemy, for example, you could set the player as the destination, instead of the Dest-1 and Dest-2 cubes we added.