Point and Click and Move!- Game Dev Series 66
Objective: Use NavMesh Agent to control player movement by mouse clicking.
We have known how to move our Player by using keyboard(WSAD). In this article, we will make our Player walk automatically to the destination where our mouse clicked.
To do this, we will give our Player the basic AI by using NavMesh Agent.
Before we add the function to our Player, we need to set the floor to verify where can walk.
Set the floor to walk
Open the Navigation tab by click the dropdown menu Window> AI> Navigation.
Select the floor collider, then click Bake in Navigation tab.
The blue area is where AI calculated that could walk. However, we need to set those display cases as obstacles by check these items to Static, otherwise our Player would walk through them.
That is the basic setting to our floor. Now we can give our Player an AI function.
Make our player move
First we need to add a NavMesh Agent component to our Player.
Then create a new script, in this script we will make it can identify where our mouse click. We can do this function by using Physic.Raycast.
First we need to set the variable to access the NavMesh Agent.
Before we declare it, we will use AI namespace to access the database of AI in Unity.
Within Update(), we will check the raycast when we left click the mouse. We will use ScreenPointToRay as the return value of mouse position.
As a movement destination, we will need to get the value of click position, which is RaycastHit.
With these value, we can get the position where our mouse clicked by using Physics.Raycast.
Now we can set the movement destination by using SetDestination(Vector3).
All done! You can control your Player by mouse clicking!