You point the way and I’ll head there.

Objective: Adding in a player's movement when we click on the ground.

Rose Owen
4 min readJul 13, 2021

In this part, we are going to be adding the functionality to be able to click on the ground and have the player move to that location.

First going to need to bake the floor with a NavMesh, this will let our char walk when we click but won’t if there isn’t a nav mesh already there, eg off the map or under an object. Open up the Navigation tab, which can be found beside the Inspector, or if it isn’t there Windows>AI>Navigation.

Next, we can select the floor we want the NavMesh on and click the bake under the Bake tab. If we want to expand on the NavMesh we can always come back here and make changes and rebake.

The floor should turn blue if you have done it correctly.

This shows where the player can walk.
As shown in this image, the mesh doesn’t go right up to the wall, limiting where the player can walk.

Now to set up the player, let’s use some primitive objects for a start to get the hang of it. Add in a 3D object of type capsule, rename it to Player and also tag as “Player”. Add a Nav Mesh Agent to the player by clicking Add Component and search for Nav Mesh Agent. This will allow the player to snap to the baked floor and move around it while also limiting where the player can go.

We can play around with these later to get a nice feel for the movement.

A way to test this is to lift the player off the ground then press the play button for the game.

As you can see the player is stuck to the ground and within the bounds of the level.

Now we can add in a script to do all the moving. Create a new script and call it Player, attach it to our player, and open it up in your preferred script editor.

Here we are going to use ray casting to be able to get the point at which we click and then tell the player to move to it. First, we will need a reference for the NavMeshAgent(NMA) that is on the player, if you try to add this right away it won’t let you though, since the NMA needs the unity engine AI it needs to be added to the very top.

Now we can make the variable to store the NMA.

Now we can GetComponent for the NMA on the player, remember to null check.

And finally, we can cast the ray from the main camera to where the mouse is, storing that in a hit variable of type RaycastHit then moving the NMA to that point.

And that’s all there is to the basics of moving by clicking.

Remember to test that everything is wrong properly and as intended And see you in the next one!

--

--

Rose Owen
Rose Owen

Written by Rose Owen

Game Developer in the making~

No responses yet