Point and Click and Move!- Game Dev Series 66

Objective: Use NavMesh Agent to control player movement by mouse clicking.

We have known how to move our Player by using keyboard(WSAD). In this article, we will make our Player walk automatically to the destination where our mouse clicked.

To do this, we will give our Player the basic AI by using NavMesh Agent.
Before we add the function to our Player, we need to set the floor to verify where can walk.

Set the floor to walk

Open the Navigation tab by click the dropdown menu Window> AI> Navigation.

Select the floor collider, then click Bake in Navigation tab.

The blue area is where AI calculated that could walk. However, we need to set those display cases as obstacles by check these items to Static, otherwise our Player would walk through them.

That is the basic setting to our floor. Now we can give our Player an AI function.

Make our player move

First we need to add a NavMesh Agent component to our Player.

Then create a new script, in this script we will make it can identify where our mouse click. We can do this function by using Physic.Raycast.

First we need to set the variable to access the NavMesh Agent.
Before we declare it, we will use AI namespace to access the database of AI in Unity.

Within Update(), we will check the raycast when we left click the mouse. We will use ScreenPointToRay as the return value of mouse position.

As a movement destination, we will need to get the value of click position, which is RaycastHit.

With these value, we can get the position where our mouse clicked by using Physics.Raycast.

Now we can set the movement destination by using SetDestination(Vector3).

All done! You can control your Player by mouse clicking!




A passionate gamer whose goal is to work in video game development.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Kotlin: Sealed Classes (enum 2.0)

AWS re:Invent 2021 AI/ML Session Guide for Builders and Architects

Tenth week as a software developer intern

Overview of .NET Core

CS373 Spring 2022: Jonathan Li

Writing Slack Command APIs in Ruby — Part 4

C/C++ vs Rust vs Go vs Python: Can you really compare them?

Tester’s Dictionary: “F” for “Flaky Tests”

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
S.J. Jason Liu

S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.

More from Medium

Creating the Main Menu

Hidden Shortcuts to Make Level Design Easier in Unity.

Creating a UI Shield Strength indicator

Day 98: Character Animation Part 1