Point & Click to Move in Unity

Point & Click Movement

In order to create a game mechanic with Click & Move, we need to use Unity’s Navigation component. Navigation is another perfect product of Unity that allows us to control the areas that the characters can move on. By using Navigational Mesh system, we can easily restrict the Player or the AI to move within a desired area, disallowing them from going outside of the area.

For information regarding Unity’s Navigation and Nav Mesh system, you can check my previous article by clicking here. The parts that have been explained on that article will be skipped on this article for avoiding repetition.

In order to make the Nav Mesh system work on the Player — so that it will search for a Nav Mesh — , we need to add the “Nav Mesh Agent” component to it.

Nav Mesh Agent Component

With this component, our game object will be able to move only on the Nav Mesh areas. Once we get into the play mode, you will realize that the Player will attach itself to the Nav Mesh. Likewise, you will realize that the game object will not move upwards or downwards in the Play mode, and will strictly move on the Nav Mesh area in the Scene view.

In order to get our game object move to the click zone, we need to use RayCasting. The idea is pretty straightforward, once we click with our mouse, a ray will be casted to the Nav Mesh, so that our game object will gather the data and move to that location.

Now that our Player is an agent, we can move the player to the clicked point, by using “NavMeshAgent.SetDestination” function. In order to access the AI library, we need to add it to the namespace :

using UnityEngine.AI;

First, we will need to access the Nav Mesh Agent component in the Player game object by declaring an agent variable and reference it in the Start.

_agent = GetComponent<NavMeshAgent>();if(_agent == null){Debug.LogError(“Player could not get the Nav Mesh Agent”);}

And then, the only thing left is to provide the point that we click with the mouse to the within the SetDestination function.

And that’s it, now our character moves by clicking. If you somehow forget the property of the game objects that should have been act like obstacles, you will notice that your character will pass through them.

Character Passing Through Objects — Not Static

Just by clicking the checkbox next to Static will notice the Nav Mesh that these objects should act like obstacles.

check Static for the objects that should act like obstacles

And then, switch to the Navigation window, click Clear and Bake again so that NavMesh will now know that these objects will act like obstacles.

Unity Developer