Moving Your Character Using a Simple Point and Click Interface in Unity

Setting up a simple point and click movement system in Unity is quite simple. Let’s take a look at the following code, in detail, which accomplishes this:

First, let’s look at the code for getting the input from the mouse:

The first line is going to check for a left click on the mouse. Button 0 corresponds to the left mouse button. If we have a mouse click we then store the position of the mouse into a Vector3.

Next let’s look at the process of finding out where we clicked and setting that destination on our navmeshagent. As we want the player to be able to click on the ground and have them move to that point, we will use a ground collider that we can ray cast against.

The first line with the ScreenPointToRay method gets us a ray that starts at the camera (the near clipping plane to be exact) and points in the direction of the point in the world that corresponds to where we clicked on the screen (the position variable).

The if statement performs a ray cast with the ray from above. If the ray hits a collider the collision information will be stored in hitInfo. Specifically, it will contain a point where the collision occurred between the ray and the collider.

Once we have that point, we set our navmeshagent’s destination to that point and watch as it moves there.

Here’s the finished product:

--

--

A Unity Developer, interested in all things Unity.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store