Unity AI Game Programming - Second Edition - Sample Chapter
Unity AI Game Programming - Second Edition - Sample Chapter
Second Edition
Unity 5 provides game and app developers with a variety
of tools to implement artificial intelligence. Leveraging
these tools via Unity's API or built-in features allows
limitless possibilities when it comes to creating your
game's worlds and characters.
"Community
Experience
Distilled"
Ray Barrera
Clifford Peters
Second Edition
Unity AI Game
Programming
ee
Sa
m
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Unity AI Game
Programming
Second Edition
Leverage the power of Unity 5 to create stunningly life-like
AI entities in your games!
Ray Barrera
Clifford Peters
Aung Sithu Kyaw has been in the technical industry for over a decade. He is
passionate about graphics programming, creating video games, writing, and sharing
knowledge with others. He holds an MSc in digital media technology from the
Nanyang Technological University (NTU), Singapore. Over the last few years, he
has worked in various positions, including research programmer and senior game
programmer. Lastly, he worked as a research associate, which involved implementing
a sensor-based real-time movie system using Unreal Development Kit. In 2011, he
founded a tech start-up, which focuses on interactive media productions and backend
server-side technologies. He is currently based in Myanmar and working on his latest
company's product, a gamified social opinion network for Myanmar.
He can be followed on Twitter at @aungsithu and LinkedIn at http://linkedin.
com/in/aungsithu.
Thet Naing Swe is the founder and CTO of Joy Dash Pte Ltd, based in Singapore.
He graduated from the University of Central Lancashire with a major in game
design and development and started his career as a game programmer at one of
the UK-based Nintendo DS game development studios. In 2010, he relocated to
Singapore and worked as a graphics programmer at the Nanyang Technological
University (NTU) on a cinematic research project.
At Joy Dash, he's responsible for interactive digital media consulting projects,
especially in education, casual games, and augmented reality projects using
Unity 3D as the main development tool. He can be reached via thetnswe@gmail.com.
Preface
In this book, we'll be exploring the world of artificial intelligence (AI) as it relates
to game development. No matter what kind of game you are developing, you will
surely find a myriad of uses for the content in this bookperhaps in ways that even
I could not imagine.
The goal of this book is not to make you an expert, as it would take many, many,
years and many more pages to do this, but to provide you with the knowledge and
tools to embark on your own AI journey. This book covers the essentials, and by the
end, you will have all that you need to implement AI in your own game, whether
you choose to expand upon the examples provided or take the knowledge and do
something new and exciting with it.
You will get the most out of this book and the examples provided by following along
and tinkering with the code and project files provided. Each chapter will provide a
conceptual background and some examples and will challenge readers to think of
ways in which they can use these concepts in their games.
Preface
Chapter 4, Finding Your Way, covers the most widely used pattern in pathfinding for
game AI agents. The agents in games need to traverse the areas of the game levels
and maneuver around obstacles along the way.
Chapter 5, Flocks and Crowds, covers flocking and crowd simulation algorithms,
allowing you to handle the unison movements of the agents in your game rather
than having to figure out the logic for each agent.
Chapter 6, Behavior Trees, covers the process of implementing a custom behavior
tree as it is one of the most common ways to implement complex and compound
AI behaviors in games.
Chapter 7, Using Fuzzy Logic to Make Your AI Seem Alive, shows you how to
let the game AI agents make decisions based on various factors in a non-binary
way. Fuzzy logic mimics the way humans make decisions.
Chapter 8, How It All Comes Together, covers an example of how various systems come
together in a single-objective game template that can be easily expanded upon.
This chapter will serve as a reference for later chapters, where we'll implement the
AI patterns in Unity.
[1]
AI and its many related studies are dense and vast, but it is really important to
understand the basics of AI being used in different domains before digging deeper
into the subject. AI is just a general term; its implementations and applications are
different for different purposes, solving different sets of problems.
Before we move on to game-specific techniques, we'll take a look at the following
research areas in AI applications that have advanced tremendously over the last
decade. Things that used to be considered science fiction are quickly becoming
science fact, such as autonomous robots. You need not look very far to find a great
example of AI advancesyour smart phone most likely has a digital assistant feature
that relies on some new AI-related technology. Here are some of the research fields
driving AI:
Computer vision: It is the ability to take visual input from sources such as
videos and cameras and analyze them to do particular operations such as
facial recognition, object recognition, and optical-character recognition.
Common sense reasoning: This is a technique that our brains can easily
use to draw answers even from the domains we don't fully understand.
Common sense knowledge is a usual and common way for us to attempt
certain questions since our brains can mix and interplay between the context,
background knowledge, and language proficiency. But making machines
to apply such knowledge is very complex and still a major challenge
for researchers.
Machine learning: This may sound like something straight out of a science
fiction movie, and the reality is not too far off. Computer programs generally
consist of a static set of instructions, which take input and provide output.
Machine learning focuses on the science of writing algorithms and programs
that can learn from the data processed by said program.
[2]
Chapter 1
[3]
Using AI in Unity
In this section, we'll walk through some of the AI techniques being used in different
types of games. We'll learn how to implement each of these features in Unity in the
upcoming chapters. Unity is a flexible engine that affords us a number of avenues to
implement AI patterns. Some are ready to go out of the box, so to speak, while we'll
have to build others from scratch. In this book, we'll focus on implementing the most
essential AI patterns within Unity so that you can get your game's AI entities up and
running quickly. Learning and implementing these techniques with this book will
serve as a fundamental first step into the vast world of AI.
[4]
Chapter 1
For example, let's take a look at an AI guard character in a typical shooting game. Its
states could be as simple as patrolling, chasing, and shooting:
States: This component defines a set of distinct states that a game entity or an
NPC can choose from (patrol, chase, and shoot)
Events: This is the component that will trigger to check the rules (guard's
visible area, distance with the player, and so on)
FSMs are a commonly used go-to AI pattern in game development because they
are relatively easy to implement, visualize, and understand. Using simple if/else
statements or switch statements, we can easily implement an FSM. It can get messy
as we start to have more states and more transitions. We'll look at how to manage a
simple FSM more in depth in Chapter 2, Finite State Machines and You.
[5]
[6]
Chapter 1
Vision, sound, and other senses can be thought of, at their most essential level, as
data. Vision is just light particles, sound is just vibrations, and so on. While we don't
need to replicate the complexity of a constant stream of light particles bouncing
around and entering our agent's eyes, we can still model the data in a way that
produces similar results.
As you might imagine, we can similarly model other sensory systems, and not just
the ones used for biological beings such as sight, sound, or smell, but even digital
and mechanical systems that can be used by enemy robots or towers, for example,
sonar and radar.
[7]
Using A* Pathfinding
There are many games where you can find monsters or enemies that follow the
player, or go to a particular point while avoiding obstacles. For example, let's take
a look at a typical RTS game. You can select a group of units and click on a location
where you want them to move or click on the enemy units to attack them. Your units
then need to find a way to reach the goal without colliding with the obstacles. The
enemy units also need to be able to do the same. Obstacles could be different for
different units. For example, an air force unit might be able to pass over a mountain,
while the ground or artillery units need to find a way around it. A* (pronounced "A
star") is a pathfinding algorithm, widely used in games because of its performance
and accuracy. Let's take a look at an example to see how it works. Let's say we want
our unit to move from point A to point B, but there's a wall in the way, and it can't go
straight towards the target. So, it needs to find a way to get to point B while avoiding
the wall. The following figure illustrates this scenario:
[8]
Chapter 1
In order to find the path from point A to point B, we need to know more about the
map such as the position of the obstacles. For this, we can split our whole map into
small tiles, representing the whole map in a grid format. The tiles can also be of other
shapes such as hexagons and triangles. Representing the whole map in a grid makes
the search area more simplified, and this is an important step in pathfinding. We can
now reference our map in a small 2D array.
Once our map is represented by a set of tiles, we can start searching for the best
path to reach the target by calculating the movement score of each tile adjacent to
the starting tile, which is a tile on the map not occupied by an obstacle, and then
choosing the tile with the lowest cost. We'll dive into the specifics of how we assign
scores and traverse the grid in Chapter 4, Finding Your Way, but this is the concept of
A* Pathfinding in a nutshell.
[9]
[ 10 ]
Chapter 1
All we have to do now is to pick up the nearest waypoint and then follow its
connected node leading to the target waypoint. Most of the games use waypoints for
pathfinding because they are simple and quite effective in using less computation
resources. However, they do have some issues. What if we want to update the
obstacles in our map? We'll also have to place waypoints for the updated map again,
as shown in the following figure:
Following each node to the target can mean that the AI character moves in a series of
straight lines from node to node. Look at the preceding figures; it's quite likely that
the AI character will collide with the wall where the path is close to the wall. If that
happens, our AI will keep trying to go through the wall to reach the next target, but
it won't be able to and will get stuck there. Even though we can smooth out the path
by transforming it to a spline and do some adjustments to avoid such obstacles, the
problem is that the waypoints don't give any information about the environment,
other than the spline is connected between the two nodes. What if our smoothed and
adjusted path passes the edge of a cliff or bridge? The new path might not be a safe
path anymore. So, for our AI entities to be able to effectively traverse the whole level,
we're going to need a tremendous number of waypoints, which will be really hard to
implement and manage.
[ 11 ]
This is a situation where a NavMesh makes the most sense. NavMesh is another graph
structure that can be used to represent our world, similar to the way we did with our
square tile-based grid or waypoints graph, as shown in the following screenshot:
A navigation mesh uses convex polygons to represent the areas in the map that an
AI entity can travel to. The most important benefit of using a navigation mesh is
that it gives a lot more information about the environment than a waypoint system.
Now we can adjust our path safely because we know the safe region in which our
AI entities can travel. Another advantage of using a navigation mesh is that we can
use the same mesh for different types of AI entities. Different AI entities can have
different properties such as size, speed, and movement abilities. A set of waypoints
is tailored for humans; AI may not work nicely for flying creatures or AI-controlled
vehicles. These might need different sets of waypoints. Using a navigation mesh can
save a lot of time in such cases.
But generating a navigation mesh programmatically based on a scene can be
a somewhat complicated process. Fortunately, Unity 3.5 introduced a built-in
navigation mesh generator as a Pro-only feature, but is now included for free in
Unity 5 personal edition. Chapter 4, Finding Your Way, will look at some of the cool
ways we can use Unity's NavMesh feature in your games and explore the additions
and improvements that came with Unity 5.
[ 12 ]
Chapter 1
Behavior trees
The behavior tree is another pattern used to represent and control the logic behind
AI agents. They have become popular for the applications in AAA games such as
Halo and Spore. Previously, we have briefly covered FSMs. They provide a very
simple, yet efficient way to define the possible behaviors of an agent, based on
the different states and transitions between them. However, FSMs are considered
difficult to scale as they can get unwieldy fairly quickly and require a fair amount of
manual setup. We need to add many states and hard-wire many transitions in order
to support all the scenarios, which we want our agent to consider. So, we need a
more scalable approach when dealing with large problems. This is where behavior
trees come in.
Behavior trees are a collection of nodes, organized in a hierarchical order, in which
nodes are connected to parents rather than states connected to each other, resembling
branches on a tree, hence the name.
[ 13 ]
The basic elements of behavior trees are task nodes, where states are the main
elements for FSMs. There are a few different tasks such as Sequence, Selector, and
Parallel Decorator. It can be a bit daunting to track what they all do. The best way
to understand this is to look at an example. Let's break the following transitions and
states into tasks, as shown in the following figure:
Let's look at a Selector task for this behavior tree. Selector tasks are represented with
a circle and a question mark inside. The selector will evaluate each child in order,
from left to right. First, it'll choose to attack the player; if the Attack task returns
success, the Selector task is done and will go back to the parent node, if there is one.
If the Attack task fails, it'll try the Chase task. If the Chase task fails, it'll try the Patrol
task. The following figure shows the basic structure of this tree concept:
[ 14 ]
Chapter 1
Test is one of the tasks in the behavior trees. The following diagram shows the use of
Sequence tasks, denoted by a rectangle with an arrow inside it. The root selector may
choose the first Sequence action. This Sequence action's first task is to check whether
the player character is close enough to attack. If this task succeeds, it'll proceed
with the next task, which is to attack the player. If the Attack task also returns
successfully, the whole sequence will return as a success, and the selector is done
with this behavior, and will not continue with other Sequence tasks. If the proximity
check task fails, the Sequence action will not proceed to the Attack task, and will
return a failed status to the parent selector task. Then the selector will choose the
next task in the sequence, Lost or Killed Player? The following figure demonstrates
this sequence:
The other two common components are parallel tasks and decorators. A parallel
task will execute all of its child tasks at the same time, while the Sequence and
Selector tasks only execute their child tasks one by one. Decorator is another type
of task that has only one child. It can change the behavior of its own child's tasks
that includes whether to run its child's task or not, how many times it should run,
and so on. We'll study how to implement a basic behavior tree system in Unity in
Chapter 6, Behavior Trees.
[ 15 ]
Summary
Game AI and academic AI have different objectives. Academic AI researches try to
solve real-world problems and prove a theory without much limitation of resources.
Game AI focuses on building NPCs within limited resources that seems to be
intelligent to the player. The objective of AI in games is to provide a challenging
opponent that makes the game more fun to play.
We learned briefly about the different AI techniques that are widely used in
games such as FSMs, sensor and input systems, flocking and crowd behaviors,
path following and steering behaviors, AI path finding, navigation meshes,
behavior trees, and fuzzy logic.
In the following chapters, we'll look at fun and relevant ways in which you can apply
these concepts to make your game more fun. We'll start off right away in Chapter 2,
Finite State Machines and You, with our own implementation of an FSM, where we'll
dive into the concepts of agents, states, and how they are applied to games.
[ 16 ]
www.PacktPub.com
Stay Connected: