After setting up the scene’s Navigation mesh in my previous post, Working With Unity’s Navigation System, I am now creating the player controls which allow the player to move their character around the level.
When the player clicks on the screen, I want their character to move as close to the point on screen at which the player clicked. This is achieved using a few bits of code dealing with different areas of Unity:
- Then all the Unity Navigation System’s internal pathfinding stuff.
First I create a new Player GameObject and a new class called “Player Control”, then add that script as well as a NavMeshAgent component to the Player object. The character model is a child of this object and is not required for movement.
Now in the “Player Control” class, I add some variables used in the movement calculations.
Since I currently only have 2 behavior states (moving and not moving) for my character, I only need 2 Enum states to switch between.
Get the references in Start( ). Not Awake( ) because Camera.main is also a reference set in Awake, and may return null if done to early.
Now in Update( ), check if the player character is moving by checking the _agent’s velocity. If it is, set it’s state to Walking, otherwise set to Idle.
After that If-Else, check for any Player input this frame telling the character to move.
Now I create an additional method called “SetDestinationToClickPosition( )” which does what the name says.
After _agent.SetDestination is called, the NavMeshAgent component will automatically start pathfinding the Player object to the set destination. Assuming you’ve set up your Nav-mesh and obstacles correctly, it will move around any obstacles in its path.
AI navigation is actually a really simple task when you made use of Unity’s system.