Point & Click to Move in Unity — Part 3: Moving Player Along the Nav Mesh
Using the nav mesh to move the player
Objective: make the layer move when clicking a point on the screen.
Here I leave you the previous articles related to this topic:
Point & Click to Move in Unity — Part 1: Player Setup
Setting up the nav mesh system
Point & Click to Move in Unity — Part 2: Creating a Raycast from Mouse Click
Detecting player click
So really quick before starting. I am gonna show you how to create the van system already explained in the first article of this topic. You just have to select the object with the collider that defines the moving area, go to window > navigation and with the object selected we have to select the option “bake”.
And we have to select the player game object and add the nav mesh agent component.
In order to access the AI functionalities we have to use the namespace UnityEngine.AI.
Then to move the player we have to create a variable (in this case called agent) of type NavMeshAgent and initialize it with the function GetComponent<NavMeshAgent>().
And the last thing to move the player is just to use the function _agent.SetDestination() and pass the mouse click position as a parameter.
And that’s it!!! We can enter in play mode, click some points and see how the navigation mesh does the work for us.