Click to Move System in Unity

Tyler Smallwood
3 min readJun 13, 2023

--

Objective: Move the Player to the location of the RaycastHit.point.

In this article we will click on the floor and have the player move to that location. To start we will need a Floor and a cube player.

For this project, we will need two scripts. One to take care of getting the location of the click and another to move the player around. We will start with PointerScript.

In the PointerScript we need to grab the new Input System Library and get a reference to the player script.

In Update we will check for input and once left mouse button click and will create a RaycastHit variable, grab the mouse position and assign it to the rayOrigin’s ScreenPointToRay. As always with Raycast, we need to check to see if it hit anything.

Next we will see if it hit the floor by using CompareTag();

Before passing in the hitInfo.Point information to the player script, we need a public method to pass it into. Now in the Player script, we will create that method that takes in a Vector3. We lock the y axis to 1f so it doesn’t go into the floor. This is for this project. Then we assign the pos to _targetDestination.

Back in PointerScript we will call this method and pass in the hitInfo.point.

Going back to the Player in Update we will check the distance of the new targetposition compared to the current position. If it is greater than 1 we will move to it using transform = Vector3.MoveTowards().

That’s all we need to do to move the player.

Vector3.MoveTowards takes care of some calculations for us so we don’t have to type it out. But if we want to use transform.Translate() we will need to do that calculation. All we need to do is subtract the target position from the current position.

Either works by I personally like MoveTowards better for this situation.

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