Point and Click to Move

In video games, one of the easiest way to allow the player to move the character is via “point and click”. In this movement system, all the player does is click somewhere on the screen, and the character will move there.

Getting Started: The Stage

Key — Blue: Movable; Green: Floor; White: the walls

When wanting to create a “point and click” movement system, all you really need is the movable object and a floor. However, in this example, I have created an enclosure so the movable object doesn’t fall off the map.

Creating the Script

Create a script by right clicking in the Project Window, going to Create, and clicking on C# Script and name your script. I chose “Player” because this script will control the movable character.

Next, create at least 2 variables:

  • Vector3 _finalDest holds the location of the destination we want the character to move to
  • bool _canMove determines if the Update should be moving the character or not.

Ray, Raycast, and RaycastHit

Because we want to move the character via “point and click”, it is important to utilize the Raycast system. In Unity, the Raycast system is a system that will shoot an invisible beam (a ray) into the scene from a point of origin. For our case, that would be the mouse cursor.

However, this doesn’t mean it will move the character or generate a position for us to move the character to. To do that, we would have to implement a similar, but different system, the RaycastHit system.

RaycastHit, unlike Raycast, takes the information from a raycast and generate information we can use in our game. In our case, this means the position of where the mouse cursor is when we clicked on the left mouse button.

Once we are able to record the position of the mouse cursor, we then can relay that information to the the Vector3 variable we created earlier (_finalDest). Furthermore, we can set the bool variable we created earlier (_canMove) to true because now the character can move.

Actually Moving the Player

With the final destination recorded, it’s time to implement the movement. Because this is a simple movement, all we’ll be doing is updating the position of the transform via the Vector3.MoveTowards method.

Moveover, we can also determine when to change the bool _canMove back to false by using the Vector3.Distance method.

Final Product

With everything combined, here is the final result: