Point & Click to Move in Unity
Objective: Create a point and click movement using Unity’s AI Navigation
Before setting up the AI Navigation, I will set all the objects in the scene to static. This will leave a perimeter around the objects that will prevent the player from passing through the object.
Next, I will bake the NavMesh on the floor collider that is set up.
Once the NavMesh is baked, it will be shown by the blue shaded areas on the floor. Notice the clear areas around the object. This is because the Objects are set as static.
Now that I have the NavMesh in place, I can move on to the coding that will allow the player to move.
On the Player Object, I will have a script named Player. Open the script and add the Library for Unity AI.
Next, I will get a reference to the Nav Mesh Agent.
Now I will add the code to move the Player along the NavMesh.
The first thing I do is check if the left mouse button is clicked Input.GetMouseButtonDown(0).
Next, I will use Physics. Raycast to cast a ray to where the mouse is clicked. Ray rayOrigin = Camera.main.DcreenPointToRay(Input.MousePosition)
Then store the info in a variable hitInfo, RaycastHit hitInfo
Lastly, I will check for a hit and set the player's destination.
Now let’s see this in action.