Point and Click Move in Unity
Having your character intelligently navigate around obstacles in a scene might seem complicated…Unity makes this process rather simple to implement!
The first thing you will need is a path to navigate. If you don’t already have one, you can set up a simple plain (or scale a cube horizontally) and use that for the ground:
Having a “ground” isn’t quite enough. The ground object (and any obstacles) must either be marked as “static” or have a “Nav Mesh Obstacle” component added.
With the object marked “Static”, you can now simply “bake” the navmesh. If your Navigation tab isn’t already showing, go to Window>AI>Navigation. Click on the Navigation tab and simply click “Bake” from within the “Bake” sub-tab:
Immediately after baking the navmesh, you’ll see a blue area within your ground. This is your navmesh. The perimeter around the navmesh that isn’t covered is due to the radius setting in the bake tab.
The next step is to add a Nav Mesh Agent component to the player:
Essentially that is it in order to give the player the ability to navigate…but the player still needs a destination.
This is where we will implement the point-click movement.
Let’s start with a new script called “Player”. Essentially, we need to get where the mouse hits the navmesh and inform the agent to move the player to that point.
In order to access the Nav Mesh Agent component on our player, we need to access the AI namespace first, then access the agent:
That’s all there is on the player side…now we need to access the position of the mouse (when the mouse button is clicked) and set that position as the destination of the player.
To access the position of where the mouse hits the baked navmesh, we need a variable of type Ray as well as RaycastHit:
We won’t fill in the hit variable as we will initialize that in our next step. Now we need to return the position (if any) that was hit by our mouse ray:
It’s important to note that Physics.Raycast returns a bool and as you may know, a method can only return a single variable…that is where the “out” parameter comes in. We created a hit variable that can now be initialized.
Putting it all together will look like this: