Point & Click to Move in Unity

Niraj Karki
2 min readJun 25, 2021

--

Stealth Game & Cinematography

Objective: Create a function to move our player to the place clicked

To make this happen you first need to create a navmesh so go to Window>AI>Navigation. Then select the Floor collider(collider that you want your player to move on) and set it to static and bake the scene and your scene will turn blue.

Now that the floor is setup, we need to prepare our player also to be able to walk on the floor so we add Nav Mesh Agent on our player.

Now that our player is ready, lets create our player script which will handle the functioning of our player.

Inside the script, add a UnityEngine.AI namespace to be able to access the navmesh library on our project.

Now create a variable to hold the reference to the nav mesh agent of the player as well as the hit position and the value of ray source position and direction

Finally inside Update, check to see if there is a left-mouse click and if the mouse button is clicked then, rayOrigin is going to store the ray value from the ray origin which is the camera position to the direction using the mouse position during click.

Now, cast a ray using Physics.Raycast and store the point of hit inside the hitInfo variable and set the destination to the position of click using the hitInfo.point

And this is the final look.

--

--

No responses yet