Day 73: Point & Click to Move in Unity

Tyler Smallwood
3 min readAug 5, 2021

--

Objective: Create the logic to move the Player

This article is the logic to find the location the player needs to move to and tomorrow’s article will use this logic along with the NavMeshAgent to actually move the player.

To begin We will need to create a Player Script and create a Player Object. Today we will be using a capsule. We need to add the Player script onto the player game object.

Inside the script and in the Update function we will need to be on the look out for the player to click the left mouse button. To do this we check for Input.GetMouseButtonDown(0). The zero indicates the left mouse button while 1 will indicate the right mouse button.

Now to check to see if we have hit anything. To do this we will be using a raycast from our mouse position. We need to save the position as a ray for the raycast. To get the position of the mouse we will use the Camera’s ScreenPointToRay(Input.mousePosition) to find the location of the mouse when clicked. This will be saved as a ray.

To check if we hit anything, we need a If statement that checks the Physics.Raycast(ray, out RaycastHit hit). The ray is what was saved earlier. We will than need to save the RaycastHit as hit. This allows to get information from it.

To check if this work we will use Debug.Log() to get the location and we’ll create primitive objects to have a visual indication of it working. We use the RaycastHit hit to get the location but using the .point at the end. hit.point returns a vector 3.

We assign the cubes transform.position to equal the hit.point location.

Every time we click now, a new cube will be spawned at that location.

Now we know our point and click system is working. Tomorrow we will cover how to use the NavMesh system to get the player move to those locations when clicked.

Thank you for reading and have a wonderful day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet