Building A Stealth Game — Using The Mouse For Movement

Photo by Pixabay from Pexels

Preparing the environment

The first thing we need to have player movement is an environment for the player to move in. This involves “baking” a NavMesh to make use of Unity’s navigation features.

The “Static” checkbox is in the upper right corner
The Bake tab of the Navigation window

Setting up the player

The next thing we need is to set up the player object, or whatever it is that we want the player to be able to move. This could just be a simple 3D object if necessary.

The Nav Mesh Agent component

Getting the mouse input

Within our script, we first want to capture when the player clicks with their mouse. We also need to be watching for this act at all times, so we need this code to go into the script’s Update method.

Determining the click point

Once we know when the player has clicked, we next need to know where they clicked. For that, we will make use of Unity Raycasts. Raycasts are sort of an invisible “ray” that shoots forth from a specific location and then proceeds in a perfectly straight line. Using them we can get the information we’re looking for.

  1. A Ray — Data type that represents a ray in Unity.
  2. A RaycastHit — Data type used to get the information from a Raycast.
  3. The Raycast function — The Physics function that will generate the data.

Moving the player

Now that we know where we want the player object to move to, we can work to make that finally happen. For that, we will be using the Nav Mesh Agent we added to the player object earlier.


And that does it. Simply setting a (valid) destination for the Nav Mesh Agent will then trigger Unity’s navigation features to cause the player object to move, navigate around obstacles, and stop at the specified destination.



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