The Sneaky Capsule: Making a click to move navigation system (Game Dev day 57)

Jack Leavey
3 min readJan 12, 2022

Now with the cutscenes being set, its time to start making this project playable. Enter the capsule gameobject, our stand in for the Player model.

This capsule serves as our player for the implementation of the movement system. He will be replaced with a detailed model later!

I assigned a new C# script to this object (Player.cs) as well as a NavMeshAgent component.

Now in order to make the capsule move, there are several things that must be done.

First off, I baked the floor so the Nav Mesh Agent can see where it can and cannot go.

To bake the floor, open Window>AI>Navigation.

Opening the Navigation Window.

Dock the window in your preferred location, and then go to the “Bake” tab inside the Navigation Window.

This is the tab.

Next, press the “Bake” button on the lower right side of the window.

Your “floor” should turn a blueish color to show that it is navmeshed.

If you have obstacles in your game (like the display cases shown here in mine) you need to make sure those objects are set to “Static” BEFORE you bake. Otherwise, you can just waltz right through them.

In the pop-up window select the option to apply to all children.

Great! Now all that remains is the coding aspect to tell the capsule where to go.

Opening up the Player.cs, I added the UnityEngine.AI library to the script.

Next, I created a private variable for the NavMeshAgent attached to the Player Gameobject (The capsule).

Assign the variable to the component in void start.

Now in Update, several “if” statements are needed to create the movement system. I utilized Raycasting to achieve this.

Raycasting is essentially shooting a “ray” or line from the camera to a specific point. The “point” is selected by left clicking in this case. It then logs the transform of the point it collided with the navmesh (the floor we just baked).

Line 19 is simply saying “If I left click”, do this.

Inside the “if” statement, we created two variables to hold our raycast information.

Line 21 is telling the ray to start from the camera and go to where the cursor is.

Line 22 is creating a variable to hold the information about the point where the ray collides with the navmesh.

Line 24 tells states that if hitInfo has an output (I.E. is holding data), do this.

Finally, Line 27 tells the navmeshagent attached to the player to go the the destination provided, which is the coordinates that we stored by left clicking.

Here’s the logic in action!

--

--

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!