Unity 2017 Game AI Programming,  Third Edition - Raymundo Barrera - E-Book

Unity 2017 Game AI Programming, Third Edition E-Book

Raymundo Barrera

0,0
40,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Use Unity 2017 to create fun and unbelievable AI entities in your games with A*, Fuzzy logic and NavMesh

Key Features

  • Explore the brand-new Unity 2017 features that makes implementing Artificial Intelligence in your game easier than ever
  • Use fuzzy logic concepts in your AI decision-making to make your characters more engaging
  • Build exciting and richer games by mastering advanced Artificial Intelligence concepts such as Neural Networks

Book Description

Unity 2017 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.

This third edition with Unity will help you break down Artificial Intelligence into simple concepts to give you a fundamental understanding of the topic to build upon. Using a variety of examples, the book then takes those concepts and walks you through actual implementations designed to highlight key concepts, and features related to game AI in Unity 5. Further on you will learn to distinguish the state machine pattern and implement one of your own. This is followed by learning how to implement a basic sensory system for your AI agent and coupling it with a Finite State Machine (FSM).

Next you'll learn how to use Unity's built-in NavMesh feature and implement your own A* pathfinding system. You will then learn how to implement simple flocks and crowd's dynamics, key AI concepts. Moving on, you will learn how to implement a behavior tree through a game-focused example. Lastly, you'll combine fuzzy logic concepts with state machines and apply all the concepts in the book to build a simple tank game.

What you will learn

  • Understand the basic terminology and concepts in game AI
  • Explore advanced AI Concepts such as Neural Networks
  • Implement a basic finite state machine using state machine behaviors in Unity 2017
  • Create sensory systems for your AI and couple it with a Finite State Machine
  • Wok with Unity 2017's built-in NavMesh features in your game
  • Build believable and highly-efficient artificial flocks and crowds
  • Create a basic behavior tree to drive a character's actions

Who this book is for

This book is intended for Unity developers with a basic understanding of C# and the Unity editor. Whether you're looking to build your first game or are looking to expand your knowledge as a game programmer, you will find plenty of exciting information and examples of game AI in terms of concepts and implementation.

Ray Barrera is a software engineer, who has spent the better part of the decade working on various serious, entertainment and educational projects in Unity. He has spoken at college campuses, and presented a talk at Unite 2017 in Austin, on app development in Unity. He is currently working in education tech as director of mobile engineering at a well-known education company. Free time outside of work is spent on a number of hobbies, including hiking, music, and cooking (primarily Mexican food). Aung Sithu Kyaw 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. 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 focusing on interactive media productions and backend server-side technologies. Thet Naing Swe has been working in the software and game industry for more than 10 years and has a passion for creating all types of games including serious, casual, casino and AAA games. He received the 1st class Honor Degree in Computer Games Development from University of Central Lancashire, UK in 2008 and started working as a game programmer at CodeMonkey studio for a year before joining NTU Singapore as a graphic programmer using UDK. He founded JoyDash Pte Ltd Singapore in 2014 where it produces casino, casual and multiplayer mobile games mainly for Myanmar market.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 265

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Unity 2017 Game AI ProgrammingThird Edition

 

 

Leverage the power of Artificial Intelligence to program smart entities for your games

 

 

 

 

 

Ray Barrera
Aung Sithu Kyaw
Thet Naing Swe

 

 

 

BIRMINGHAM - MUMBAI

Unity 2017 Game AI Programming Third Edition

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Kunal ChaudhariAcquisition Editor: Reshma RamanContent Development Editor: Francis CarneiroTechnical Editor: Murtaza TinwalaCopy Editor: Safis EditingProject Coordinator: Devanshi DoshiProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jason MonteiroProduction Coordinator: Shraddha Falebhai

First published: July 2013 Second edition: September 2015 Third edition: January 2018

Production reference: 1090118

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78847-790-1

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the authors

Ray Barrera is a software engineer, who has spent the better part of the decade working on various serious, entertainment and educational projects in Unity. He has spoken at college campuses, and presented a talk at Unite 2017 in Austin, on app development in Unity. He is currently working in education tech as director of mobile engineering at a well-known education company. Free time outside of work is spent on a number of hobbies, including hiking, music, and cooking (primarily Mexican food).

I'd like to thank my friends and family and my wonderful fiancee, Cara, who is the most supportive and amazing partner a man could wish for. I would also like to dedicate this book to my amazing mother, Maria, whom I lost earlier this year. She shaped me into the man I am today, and I could not be more thankful to her. I love you and miss you, mom.

 

Aung Sithu Kyaw 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. 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 focusing on interactive media productions and backend server-side technologies.

 

Thet Naing Swe has been working in the software and game industry for more than 10 years and has a passion for creating all types of games including serious, casual, casino and AAA games.

He received the 1st class Honor Degree in Computer Games Development from University of Central Lancashire, UK in 2008 and started working as a game programmer at CodeMonkey studio for a year before joining NTU Singapore as a graphic programmer using UDK. He founded JoyDash Pte Ltd Singapore in 2014 where it produces casino, casual and multiplayer mobile games mainly for Myanmar market.

About the reviewer

Davide Aversa completed his Master in Robotics and Artificial Intelligence and Ph.D. in Computer Science at La Sapienza University of Rome where he has been involved in research applied to pathfinding and decision making for digital games characters, and computational creativity.

 

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

The Basics of AI in Games

Creating the illusion of life

Neural Networks

Leveling up your game with AI

Using AI in Unity

Defining the agent

Finite State Machines

Seeing the world through our agent's eyes

Path following and steering

Dijkstra's algorithm

Using A* Pathfinding

IDA* Pathfinding

Using Navigation Mesh

Flocking and crowd dynamics

Behavior trees

Thinking with fuzzy logic

Summary

Finite State Machines and You

Finding uses for FSMs

Creating state machine behaviors

Creating the AnimationController asset

Layers and parameters

The animation controller inspector

Bringing behaviors into the picture

Creating our very first state

Transitioning between states

Setting up our player tank

Creating the enemy tank

Choosing transitions

Making the cogs turn

Setting conditions

Driving parameters via code

Making our enemy tank move

Testing

Summary

Implementing Sensors

Basic sensory systems

Cone of sight

Hearing, feeling, and smelling using spheres

Expanding AI through omniscience

Getting creative with sensing

Setting up the scene

Setting up the player tank and aspect

Implementing the player tank

Implementing the Aspect class

Creating an AI character

Using the Sense class

Giving a little perspective

Touching is believing

Testing the results

Summary

Finding Your Way

Following a path

The path script

Using the path follower

Avoiding obstacles

Adding a custom layer

Obstacle avoidance

A* Pathfinding

Revisiting the A* algorithm

Implementation

The Node class

Establishing the priority queue

Setting up our grid manager

Diving into our A* implementation

Implementing a TestCode class

Testing it in the sample scene

Testing all the components

A* vs IDA*

Navigation mesh

Inspecting our map

Navigation Static

Baking the navigation mesh

Using the NavMesh agent

Setting a destination

Making sense of Off Mesh Links

Summary

Flocks and Crowds

Learning the origins of flocks

Understanding the concepts behind flocks and crowds

Using the Reynolds algorithm

Implementing the FlockController

The flock target

The scene layout

Using crowds

Implementing a simple crowd simulation

Using the CrowdAgent component

Adding some fun obstacles

Summary

Behavior Trees

Learning the basics of behavior trees

Understanding different node types

Defining composite nodes

Understanding decorator nodes

Describing the leaf node

Evaluating the existing solutions

Implementing a basic behavior tree framework

Implementing a base Node class

Extending nodes to selectors

Moving on to sequences

Implementing a decorator as an inverter

Creating a generic action node

Testing our framework

Planning ahead

Examining our scene setup

Exploring the MathTree code

Executing the test

HomeRock card game example

The scene setup

The enemy state machine

Testing the game

Summary

Using Fuzzy Logic to Make Your AI Seem Alive

Defining fuzzy logic

Picking fuzzy systems over binary systems

Using fuzzy logic

Implementing a simple fuzzy logic system

Expanding the sets

Defuzzifying the data

Using the resulting crisp data

Using a simpler approach

The morality meter example

The question and answer classes

Managing the conversation

Loading up the questions

Handling user input

Calculating the results

Scene setup

Testing the example

Finding other uses for fuzzy logic

Merging with other concepts

Creating a truly unique experience

Summary

How It All Comes Together

Setting up the rules

Creating the towers

Making the towers shoot

Setting up the tank

Bonus tank abilities

Setting up the environment

Testing the example

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Welcome to the wonderful world of AI in games, or, more specifically, AI in Unity.  This book focuses on the Unity implementations of AI-related features and also delves into the basic concepts behind those features. It even provides ground-up examples of some of them. Along the way, this book provides example projects and sample code for the reader to follow, play with, and, hopefully, build upon in their own projects.

Who this book is for

While the reader is not expected to be an advanced programmer, this book does assume some base-level knowledge of C# and scripting in Unity. That said, the sample code provided is well commented and explained throughout the book in a very detailed way, in order to describe the reason behind each decision and every line of code. Familiarity with some of the algorithms provided is certainly helpful, but by no means required. This book will explain the theory and origin of the concepts and then delve into implementations that highlight the core functionality we're looking for. Extraneous code is kept to a minimum to allow the reader to truly focus on the book's main objective—learning AI game programming in Unity.

What this book covers

Chapter 1, The Basics of AI in Games, gets the reader up to speed with the basic terminology we'll be working with. In order to build up to the more advanced concepts in the book, we first lay the groundwork and expectations for the following chapters. This introductory chapter provides a preview of some of the concepts covered and prepares the reader with the necessary knowledge to be successful in  the sample projects and code to follow.

Chapter 2, Finite State Machines and You, jumps right into one of the most essential concepts in game AI--the finite state machine. The chapter starts with a conceptual overview and then dives into an implementation of a state machine in Unity using the built-in features, such as Mecanim and StateMachineBehaviours. This chapter is the first to take the user through an actual example and sets the tone for how future chapters will explain the concepts they cover.

Chapter 3, Implementing Sensors, builds on the concept of the AI agent by providing the reader the knowledge and techniques to make their AI more believable. In this chapter, the reader learns how to implement sensing for their agents, allowing them to collect data and information from their virtual surroundings, thus enabling more complex interactions with their environment. The output of the agent is only as good as the input, and this chapter ensures that the reader can implement sensing mechanisms to give AI behaviors solid inputs to base their algorithms on.

Chapter 4, Finding Your Way, takes the reader's knowledge to the next level. With the skills from the previous three chapters to build on, the reader is now given the tools to have their AI agent navigate the game world. A few different alternatives are explained in detail, such as node-based pathfinding, the near-standard A* algorithm approach, and finally, Unity's NavMesh system. Examples are provided for each, and the user is given the necessary knowledge to pick the right approach for each situation.

Chapter 5, Flocks and Crowds, covers the history and implementation of a standard flocking algorithm. Along with some history on the topic, the user is walked through a sample project that implements flocking to create convincing boid systems to model birds, fish, locusts, or any other flocking behavior. In the later portion of the chapter, the reader is introduced to implementing simple crowd dynamics using Unity's NavMesh system. Once again, sample scenes are provided to illustrate the different implementations.

Chapter 6, Behavior Trees, showcases another handy tool in the AI game programmer's tool belt: the behavior tree. The chapter teaches readers the concepts behind behavior trees, walks them through a custom implementation, and applies the knowledge learned in two examples: a simple math-based example and a more fun and frankly silly example we call HomeRock, which emulates a popular online card game to showcase behavior trees in action.

Chapter 7, Using Fuzzy Logic to Make Your AI Seem Alive, sets the stage with a long and descriptive title, right? This chapter covers the fundamental concepts in fuzzy logic and the approach for converting fuzzy values to concrete values and explains a simple approach for implementing fuzzy logic in Unity. The first example illustrates the simplest possible version of the concepts, and the second example illustrates a morality/faction system like you'd find in an RPG to illustrate the usefulness of fuzzy logic.

Chapter 8, How It All Comes Together, takes concepts the reader has learned throughout the book and throws them into a sample tower defense example project. This chapter illustrates how, by taking a handful of AI techniques, you can quickly throw together a game that implements AI NPCs and enemies and gives them rudimentary decision-making abilities.

To get the most out of this book

Be sure to download all the sample code for this book! Following along with the examples is crucial to understanding all the concepts covered.

Brush up on your C# if you're rusty. This book will do its best to not leave anyone behind, but a beginner to intermediate level of understanding of C# and Unity scripting is assumed.

Experiment! This book covers the core concepts, but all the examples are set up for experimentation. The reader is encouraged to build upon the given examples, to tweak values, assets, and code to achieve new outcomes.

Be patient. Depending on your skill level or experience, you may find some of these concepts a bit daunting. Be sure to follow the instructions closely, and examine all the provided sample code thoroughly. AI can be a daunting subject, and while this book aims to make you feel comfortable with the core concepts, it's OK if you need to read an example more than once to fully understand all the nuances.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Unity-2017-Game-AI-Programming-Third-Edition. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/Unity2017GameAIProgrammingThirdEdition_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

The Basics of AI in Games

Artificial Intelligence (AI) is a rich and complex topic. At first glance, it can seem intimidating. The uses for it are diverse, ranging from robotics to statistics and to (more relevantly for us) entertainment, more specifically, video games. Our goal in this book will be to demystify the subject by breaking down the usage of AI into relatable, applicable solutions, and to provide accessible examples that illustrate the concepts in ways that cut through the noise and go straight for the core ideas. This book will lead you head first into the world of AI, and will introduce you to the most important concepts to start you on your AI journey.

This chapter will give you a little background on AI in academics, traditional domains, and game-specific applications. Here are the topics we'll cover:

Exploring how the application and implementation of AI in games is different from other domains

Looking at the special requirements for AI in games

Looking at the basic AI patterns used in games

This chapter will serve as a reference for later chapters, where we'll implement AI patterns in Unity.

Creating the illusion of life

Before diving in much deeper, we should stop for a moment and define intelligence. Intelligence is simply the ability to learn something then apply that knowledge. Artificial intelligence, at least for our purposes, is the illusion of intelligence. Our intelligent entities need not necessarily learn things, but must at the very least convince the player that they are learning things. I must stress that these definitions fit game AI specifically. As we'll discover later in this section, there are many applications for AI outside of games, where other definitions are more adequate. 

Intelligent creatures, such as humans and other animals, learn from their environment. Whether it's through observing something visually, hearing it, feeling it, and so on, our brains convert those stimuli into information that we process and learn from. Similarly, our computer-created AI must observe and react to its environment to appear smart. While we use our eyes, ears, and other means to perceive, our game's AI entities have a different set of sensors at their disposal. Rather than using big, complex brains like ours, our code will simulate the processing of that data and the behaviors that model a logical and believable reaction to that data.

AI and its many related studies are dense and varied, but it is 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 various implementations and applications are different for different needs and for solving different sets of problems.

Before we move onto game-specific techniques, let's take a look at the following research areas in AI applications that have advanced tremendously over the last several decades. Things that used to be considered science fiction are quickly becoming science fact, such as autonomous robots and self-driving cars. You need not look very far to find great examples of advances in AI—your smartphone most likely has a digital assistant feature that relies on some new AI-related technology. It probably knows your schedule better than you do! Here are some of the research fields driving AI:

Computer vision

: This is the ability to take visual input from sources, such as video and photo cameras, and analyze it to perform particular operations such as facial recognition, object recognition, and optical-character recognition. Computer vision is at the forefront of advances in autonomous vehicles. Cars with even relatively simple systems, such as collision mitigation and adaptive cruise control, use an array of sensors to determine depth contextually to help prevent collisions.

Natural language processing (NLP)

: This is the ability that allows a machine to read and understand the languages as we normally write and speak. The problem is that the languages we use today are difficult for machines to understand. There are many different ways to say the same thing, and the same sentence can have different meanings according to the context. NLP is an important step for machines since they need to understand the languages and expressions we use before they can process them and respond accordingly. Fortunately, there's an enormous number of datasets available on the web that can help researchers by doing automatic analysis of a language.

Common sense reasoning

: This is a technique that our brains can easily use to draw answers even from 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 context, background knowledge, and language proficiency. But making machines 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, and apply that for future learning.

Neural Networks

After years and years of research and development, AI is a rapidly expanding field. As consumer-level computer hardware becomes more and more powerful, developers are finding new and exciting ways to implement ever complex forms of AI in all kinds of applications. One such AI concept is Neural Networks, a subset of machine learning that we mentioned in the previous section. Neural Networks enable computers to "learn", and through repeated training become more and more efficient and effective at solving any number of problems. A very popular exercise for testing Neural Network machine learning is teaching an AI how to discern the value of a set of handwritten numbers.

In what we call supervised learning, we provide our Neural Network a set of training data. In the handwritten number scenario, we pass in hundreds or thousands of images collected from any source containing handwritten numbers. Using a process called back propagation, the network can adjust itself with the values and data it just "learned" to create a more accurate prediction in the next iteration of the learning cycle.

Believe it or not, the concept of Neural Networks has been around since the 1940s, with the first implementation happening in the early 1950s. The concept is fairly straightforward at a high level—a series of nodes, called neurons, are connected to one another via their axons, or connectors. If these terms sound familiar, it's because they were borrowed from brain cell structures with the same names, and in some ways, similar functions.

Layers of these networks are connected to one another. Generally, there is an input layer, a hidden layer, and an output layer. This structure is represented by the following diagram:

A basic neural net structure

The input, which represents the data the agent is taking in, such as images, audio, or anything else, is passed through a hidden layer, which converts the data into something the program can use and then sends that data through to the output layer for final processing.

In neural net machine learning, not all input is equal; at least, it shouldn't be. Input is weighed before being passed into the hidden layer. While it's generally okay to start with equal weights, the program can then self-adjust those weights through each iteration using back propagation. Put simply, weights are how likely the input data is to be useful in the prediction. 

After many iterations of training, the AI will then be able to tackle brand new data sets, even if it has never encountered them before! While the use for machine learning in games is still limited, the field continues to expand and is a very popular topic these days. Make sure not to miss the train and check out Machine Learning for Developers by Rodolfo Bonnin to deep dive into all things related to machine learning.

Leveling up your game with AI

AI in games dates back all the way to the earliest games, even as far back as Namco's arcade hit Pac-Man. The AI was rudimentary at best, but even in Pac-Man, each of the enemies—Blinky, Pinky, Inky, and Clyde—had unique behaviors that challenged the player in different ways. Learning those behaviors and reacting to them adds a huge amount of depth to the game and keeps players coming back, even after over 30 years since its release.

It's the job of a good game designer to make the game challenging enough to be engaging, but not so difficult that a player can never win. To this end, AI is a fantastic tool that can help abstract the patterns that entities in games follow to make them seem more organic, alive, and real. Much like an animator through each frame or an artist through his brush, a designer or programmer can breathe life into their creations via clever use of the AI techniques covered in this book.

The role of AI in games is to make games fun by providing challenging entities to compete with, and interesting non-player characters (NPCs) that behave realistically inside the game world. The objective here is not to replicate the whole thought process of humans or animals, but merely to sell the illusion of life and make NPCs seem intelligent by having them react to the changing situations inside the game world in a way that makes sense to the player.

Technology allows us to design and create intricate patterns and behaviors, but we're not yet at the point where AI in games even begins to resemble true human behavior. While smaller, more powerful chips, buckets of memory, and even distributed computing have given programmers a much higher computational ceiling to dedicate to AI, at the end of the day, resources are still shared between other operations such as graphics rendering, physics simulation, audio processing, animation, and others, all in real time. All these systems have to play nice with each other to achieve a steady frame rate throughout the game. Like all the other disciplines in game development, optimizing AI calculations remains a huge challenge for AI developers.

Using AI in Unity

In this section, we'll walk you 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 provides a number of approaches to implement AI patterns. Some are ready to go out of the box, so to speak, while others we'll have to build 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 the techniques within this book will serve as a fundamental first step in the vast world of AI. Many of the concepts we will cover in this book, such as pathfinding and Navigation Meshes, are interconnected and build on top of one another. For this reason, it's important to get the fundamentals right first before digging into the high-level APIs that Unity provides.

Defining the agent

Before jumping into our first technique, we should be clear on a key term you'll see used throughout the book—the agent. An agent, as it relates to AI, is our artificially intelligent entity. When we talk about our AI, we're not specifically referring to a character, but an entity that displays complex behavior patterns, which we can refer to as non-random, or in other words, intelligent. This entity can be a character, creature, vehicle, or anything else. The agent is the autonomous entity, executing the patterns and behaviors we'll be covering. With that out of the way, let's jump in.

Finite State Machines

FiniteState Machines (FSM) can be considered one of the simplest AI models, and they are commonly used in games. A state machine basically consists of a set number of states that are connected in a graph by the transitions between them. A game entity starts with an initial state and then looks out for the events and rules that will trigger a transition to another state. A game entity can only be in exactly one state at any given time.

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:

There are basically four components in a simple FSM:

States