Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

NPC to travel to destination while avoiding obstacles

The introduction of Unity’s NavMeshAgent has greatly simplified the coding for Non-Player Character (NPC) and enemy agent behaviors. In this recipe, we’ll add some wall obstacles (scaled cubes) and a NavMeshSurface so that Unity knows not to try to walk through walls.

We’ll then add a NavMeshAgent component to our NPC GameObject and tell it to head to a stated destination location by intelligently planning and following a path while avoiding the wall obstacles.

When the NavMeshSurface is added, the Scene panel displays the blue-shaded walkable areas, as well as unshaded, non-walkable areas at the edge of the terrain and around each of the two wall objects:

Figure 12.1: Example of an NPC avoiding obstacles

Getting ready

The required SandAlbedo texture terrain can be found in the 12_01 folder.

You will also need to install the AI Navigation package, but first, make sure you are signed...

NPC to seek or flee from a moving object

Rather than a destination that is fixed when the scene starts, let’s allow the Capsule-destination object to be moved by the player while the scene is running. In every frame, we’ll get our NPC arrow to reset the destination of NavMeshAgent to wherever Capsule-destination has been moved to.

Getting ready

This recipe adds to the previous one, so make a copy of that project folder and do your work for this recipe with that copy.

How to do it...

To make an NPC seek or flee from a moving object, follow these steps:

  1. With the Capsule-destination GameObject selected in the Hierarchy panel, add a Rigid Body Physics component to it by going to Component | Physics | Rigidbody.
  2. In the Inspector panel for the Capsule-destination GameObject, check the Freeze Position constraint for the Y axis in the Constraints options of the RigidBody component. This will prevent the object from moving in the Y axis due to...

Point-and-click move to object

Another way to choose the destination for our Sphere-arrow GameObject is by the user clicking on an object on the screen, and then the Sphere-arrow GameObject moving to the location of the clicked object:

Figure 12.7: Example of point-and-click move to object

Getting ready

This recipe adds to the first recipe in this chapter, so make a copy of that project folder and do your work for this recipe with that copy.

How to do it...

To create an object-based point-and-click mini-game, do the following:

  1. In the Inspector panel, add the Player tag to the Sphere-arrow GameObject.
  2. Delete the two 3D cubes and the 3D Capsule-destination from the scene.
  3. Remove the ArrowNCPMovement C# script as a component from the Sphere-arrow Game Object.
  4. Create three GameObjects – a 3D cube, a 3D sphere, and a 3D cylinder – and place them in different positions within the terrain.
  5. On the NavMeshSurface component...

Point-and-click move to tile

Rather than clicking specific objects to indicate the target for our AI-controlled agent, we can create a grid of 3D plane (tile) objects to allow the player to click any tile to indicate a destination for the AI controller character.

So, any location can be clicked, rather than only one of a few specific objects:

Figure 12.8: Example of point-and-click move to tile with a 3D plane grid

Getting ready

This recipe adds to the previous one, so make a copy of that project folder and do your work for this recipe with that copy.

For this recipe, we have prepared a red-outlined black square texture image named square_outline.png in a folder named Textures in the 12_04 folder.

How to do it...

To create a point-and-click game by setting GameObjects to a selected tile, do the following:

  1. Delete your 3D cube, sphere, and cylinder GameObjects from the scene.
  2. Remove the script component ArrowNCPMovment from the Sphere...

Point-and-click raycast with user-defined, higher-cost navigation areas

Rather than indicating a desired destination by clicking an object or tile, we can use Unity’s built-in Physics.Raycast(...) method to identify which Vector3 (x,y,z) position relates to the object surface in the game.

This involves translating from the 2D (x,y) screen position to an imagined 3D “ray” from the user’s point of view, through the screen, into the game world, and identifying which object (polygon) it hits first.

This recipe will use Physics.Raycast to set the position of the location that’s clicked on as the new destination for a NavMeshAgent controller object. The actual route that’s followed can be influenced by defining navigation mesh areas of different costs. For example, walking through mud or swimming through water can have a higher cost, since they would take longer, so the AI NavMeshAgent can calculate the lowest-cost route, which may not be...

NPC NavMeshAgent to follow waypoints in sequence

Waypoints are often used as guides to help autonomously moving NPCs and enemies follow a path in a general way but still be able to respond with other directional behaviors, such as fleeing or sensing if friends/predators/prey are nearby. The waypoints are arranged in a sequence so that when the character reaches or gets close to a waypoint, it will select the next waypoint in the sequence as the target location to move toward. This recipe will demonstrate an arrow object moving toward a waypoint. Then, when it gets close enough, it will choose the next waypoint in the sequence as the new target destination. When the last waypoint has been reached, it will start heading toward the first waypoint once more.

Since Unity’s NavMeshAgent has simplified coding NPC behavior, our work in this recipe basically becomes finding the position of the next waypoint and then telling NavMeshAgent that this waypoint is its new destination...

Creating a movable NavMesh Obstacle

Sometimes, we want a moving object to slow down or to prevent an AI NavMeshAgent-controlled character from passing through an area of our game. Or, perhaps we want something such as a door or drawbridge to sometimes permit travel, and not at other times. We can’t “bake” these objects into the NavMesh at design time since we want to change them during runtime.

While computationally more expensive (that is, they slow down your game more than static, non-navigable objects), NavMesh Obstacles are components that can be added to GameObjects, and these components can be enabled and disabled like any other component.

A special property of NavMesh Obstacles is that they can be set to “carve out” areas of the NavMesh, causing NavMeshAgents to then recalculate routes that avoid these carved-out parts of the mesh.

In this recipe, you’ll create a player-controlled red cube that you can move to obstruct an...

Joining several NavMeshes with a single NavMeshSurface

We have a single NavMeshSurface component in our terrain. However, what a NavMeshSurface does is look for navigable meshes in the scene with a similar orientation – that means close to horizontal for the orientation of the GameObject that has a NavMeshSurface component. In this recipe, we’ll first add a large cube to the scene, and then rebake the NavMesh to see how the top of the cube gets its own NavMesh. We’ll then tilt the cube (a little) to see how NavMeshes can join up if the gap and slope between them are not too great:

Figure 12.17: Joined NavMeshes allowing travel up the slope

Getting ready

This recipe adds to the first recipe in this chapter, so make a copy of that project folder and do your work for this recipe with that copy.

How to do it...

To work with non-horizontal NavMeshes, follow these steps:

  1. Add a new 3D cube to the scene, named Cube-slope. Scale this...

Further reading

The following are sources that provide further information about Unity and AI navigation. Some NavMesh features (such as NavMesh Links and dynamic mesh baking at runtime) are not part of the standard Unity installation and require additional installation. You can learn more about these components, their APIs, and how to install them here: https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/.

The Unity Technologies NavMesh tutorial can be found here: https://learn.unity.com/tutorial/from-waypoints-to-navmesh.

While the Unity development community has been asking for 2D NavMeshes for some years now, they’ve not yet been released as a core feature. There is a lot of online information about how to write your own pathfinding system that would work in 2D. A working project (last checked in November 2023) that extends the Unity navigation components can be found here:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy