Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Unity 5.x Game AI Programming Cookbook
Unity 5.x Game AI Programming Cookbook

Unity 5.x Game AI Programming Cookbook: Build and customize a wide range of powerful Unity AI systems with over 70 hands-on recipes and techniques

Arrow left icon
Profile Icon Jorge Palacios Profile Icon Jorge Elieser P Garrido
Arrow right icon
$9.99 $39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8 (4 Ratings)
eBook Mar 2016 278 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Jorge Palacios Profile Icon Jorge Elieser P Garrido
Arrow right icon
$9.99 $39.99
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8 (4 Ratings)
eBook Mar 2016 278 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Unity 5.x Game AI Programming Cookbook

Chapter 2. Navigation

In this chapter, we will cover the following recipes:

  • Representing the world with grids
  • Representing the world with Dirichlet domains
  • Representing the world with points of visibility
  • Representing the world with a self-made navigation mesh
  • Finding your way out of a maze with DFS
  • Finding the shortest path in a grid with BFS
  • Finding the shortest path with Dijkstra
  • Finding the best-promising path with A*
  • Improving A* for memory: IDA*
  • Planning navigation in several frames: time-sliced search
  • Smoothing a path

Introduction

In this chapter, we will learn path-finding algorithms for navigating complex scenarios. Game worlds are usually complex structures; whether a maze, an open world, or everything in between. That's why we need different techniques for approaching these kinds of problems.

We'll learn some ways of representing the world using different kinds of graph structures, and several algorithms for finding a path, each aimed at different situations.

It is worth mentioning that path-finding algorithms rely on techniques such as Seek and Arrive, learnt in the previous chapter, in order to navigate the map.

Representing the world with grids

A grid is the most used structure for representing worlds in games because it is easy to implement and visualize. However, we will lay the foundations for advanced graph representations while learning the basis of graph theory and properties.

Getting ready

First, we need to create an abstract class called Graph, declaring the virtual methods that every graph representation implements. It is done this way because, no matter how the vertices and edges are represented internally, the path-finding algorithms remain high-level, thus avoiding the implementation of the algorithms for each type of graph representation.

This class works as a parent class for the different representations to be learned in the chapter and it's a good starting point if you want to implement graph representations not covered in the book.

The following is the code for the Graph class:

  1. Create the backbone with the member values:
    using UnityEngine;
    using System.Collections;
    using System...

Representing the world with Dirichlet domains

Also called a Voronoi polygon, a Dirichlet domain is a way of dividing space into regions consisting of a set of points closer to a given seed point than to any other. This graph representation helps in distributing the space using Unity's primitives or existing meshes, thus not really adhering to the definition, but using the concept as a means to an end. Dirichlet domains are usually mapped using cones for delimiting the area of a given vertex, but we're adapting that principle to our specific needs and tool.

Representing the world with Dirichlet domains

Example of a Voronoi Diagram or Voronoi Polygon

Getting ready

Before building our new Graph class, it's important to create the VertexReport class, make some modifications to our Graph class, and add the Vertex tag in the project:

  1. Prepend the VertexReport class to the Graph class specification, in the same file:
    public class VertexReport
    {
        public int vertex;
        public GameObject obj;
        public VertexReport(int vertexId...

Representing the world with points of visibility

This is another widely-used technique for world representation based on points located throughout the valid area of navigation, whether manually placed or automated via scripting. We'll be using manually-placed points connected automatically via scripting.

Getting ready

Just like the previous representation, it's important to have several things in order before continuing:

  • Having the Edge class prepended to the Graph class in the same file
  • Defining the GetEdges function in the Graph class
  • Having the Vertex class

Note

The vertex objects in the scene must have a collider component attached to them, as well as the Vertex tag assigned. It's recommended for them to be unitary Sphere primitives.

How to do it...

We'll be creating the graph representation class as well as a custom Vertex class:

  1. Create the VertexVisibility class deriving from Vertex:
    using UnityEngine;
    using System.Collections.Generic;
    
    public class VertexVisibility : Vertex...

Representing the world with a self-made navigation mesh

Sometimes, a custom navigation mesh is necessary for dealing with difficult situations such as different types of graphs, but placing the graph's vertices manually is troublesome because it requires a lot of time to cover large areas.

We will learn how to use a model's mesh in order to generate a navigation mesh based on its triangles' centroids as vertices, and then leverage the heavy lifting from the previous recipe we learned.

Getting ready

This recipe requires some knowledge of custom editor scripting and understanding and implementing the points of visibility in the graph representation. Also, it is worth mentioning that the script instantiates a CustomNavMesh game object automatically in the scene and requires a prefab assigned, just like any other graph representation.

Finally, it's important to create the following class, deriving from GraphVisibility:

using UnityEngine;
using System.Collections;
using System...

Finding your way out of a maze with DFS

The Depth-First Search (DFS) algorithm is a path-finding technique suitable for low-memory devices. Another common use is to build mazes with a few modifications to the list of nodes visited and discovered, however the main algorithm stays the same.

Getting ready

This is a high-level algorithm that relies on each graph's implementation of the general functions, so the algorithm is implemented in the Graph class.

It is important to

How to do it...

Even though this recipe is only defining a function, please take into consideration the comments in the code to understand the indentation and code flow for effectively:

  1. Declare the GetPathDFS function:
    public List<Vertex> GetPathDFS(GameObject srcObj, GameObject dstObj)
    {
        // next steps
    }
  2. Validate if input objects are null:
    if (srcObj == null || dstObj == null)
        return new List<Vertex>();
  3. Declare and initialize the variables we need for the algorithm:
    Vertex src = GetNearestVertex(srcObj.transform...

Introduction


In this chapter, we will learn path-finding algorithms for navigating complex scenarios. Game worlds are usually complex structures; whether a maze, an open world, or everything in between. That's why we need different techniques for approaching these kinds of problems.

We'll learn some ways of representing the world using different kinds of graph structures, and several algorithms for finding a path, each aimed at different situations.

It is worth mentioning that path-finding algorithms rely on techniques such as Seek and Arrive, learnt in the previous chapter, in order to navigate the map.

Representing the world with grids


A grid is the most used structure for representing worlds in games because it is easy to implement and visualize. However, we will lay the foundations for advanced graph representations while learning the basis of graph theory and properties.

Getting ready

First, we need to create an abstract class called Graph, declaring the virtual methods that every graph representation implements. It is done this way because, no matter how the vertices and edges are represented internally, the path-finding algorithms remain high-level, thus avoiding the implementation of the algorithms for each type of graph representation.

This class works as a parent class for the different representations to be learned in the chapter and it's a good starting point if you want to implement graph representations not covered in the book.

The following is the code for the Graph class:

  1. Create the backbone with the member values:

    using UnityEngine;
    using System.Collections;
    using System.Collections...

Representing the world with Dirichlet domains


Also called a Voronoi polygon, a Dirichlet domain is a way of dividing space into regions consisting of a set of points closer to a given seed point than to any other. This graph representation helps in distributing the space using Unity's primitives or existing meshes, thus not really adhering to the definition, but using the concept as a means to an end. Dirichlet domains are usually mapped using cones for delimiting the area of a given vertex, but we're adapting that principle to our specific needs and tool.

Example of a Voronoi Diagram or Voronoi Polygon

Getting ready

Before building our new Graph class, it's important to create the VertexReport class, make some modifications to our Graph class, and add the Vertex tag in the project:

  1. Prepend the VertexReport class to the Graph class specification, in the same file:

    public class VertexReport
    {
        public int vertex;
        public GameObject obj;
        public VertexReport(int vertexId, GameObject obj...

Representing the world with points of visibility


This is another widely-used technique for world representation based on points located throughout the valid area of navigation, whether manually placed or automated via scripting. We'll be using manually-placed points connected automatically via scripting.

Getting ready

Just like the previous representation, it's important to have several things in order before continuing:

  • Having the Edge class prepended to the Graph class in the same file

  • Defining the GetEdges function in the Graph class

  • Having the Vertex class

Note

The vertex objects in the scene must have a collider component attached to them, as well as the Vertex tag assigned. It's recommended for them to be unitary Sphere primitives.

How to do it...

We'll be creating the graph representation class as well as a custom Vertex class:

  1. Create the VertexVisibility class deriving from Vertex:

    using UnityEngine;
    using System.Collections.Generic;
    
    public class VertexVisibility : Vertex
    {
        void Awake...

Representing the world with a self-made navigation mesh


Sometimes, a custom navigation mesh is necessary for dealing with difficult situations such as different types of graphs, but placing the graph's vertices manually is troublesome because it requires a lot of time to cover large areas.

We will learn how to use a model's mesh in order to generate a navigation mesh based on its triangles' centroids as vertices, and then leverage the heavy lifting from the previous recipe we learned.

Getting ready

This recipe requires some knowledge of custom editor scripting and understanding and implementing the points of visibility in the graph representation. Also, it is worth mentioning that the script instantiates a CustomNavMesh game object automatically in the scene and requires a prefab assigned, just like any other graph representation.

Finally, it's important to create the following class, deriving from GraphVisibility:

using UnityEngine;
using System.Collections;
using System.Collections.Generic...

Finding your way out of a maze with DFS


The Depth-First Search (DFS) algorithm is a path-finding technique suitable for low-memory devices. Another common use is to build mazes with a few modifications to the list of nodes visited and discovered, however the main algorithm stays the same.

Getting ready

This is a high-level algorithm that relies on each graph's implementation of the general functions, so the algorithm is implemented in the Graph class.

It is important to

How to do it...

Even though this recipe is only defining a function, please take into consideration the comments in the code to understand the indentation and code flow for effectively:

  1. Declare the GetPathDFS function:

    public List<Vertex> GetPathDFS(GameObject srcObj, GameObject dstObj)
    {
        // next steps
    }
  2. Validate if input objects are null:

    if (srcObj == null || dstObj == null)
        return new List<Vertex>();
  3. Declare and initialize the variables we need for the algorithm:

    Vertex src = GetNearestVertex(srcObj.transform...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Empower your agent with decision making capabilities using advanced minimaxing and Negamaxing techniques
  • Discover how AI can be applied to a wide range of games to make them more interactive.
  • Instigate vision and hearing abilities in your agent through collider based and graph based systems

Description

Unity 5 comes fully packaged with a toolbox of powerful features to help game and app developers create and implement powerful game AI. 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 practical Cookbook covers both essential and niche techniques to help you be able to do that and more. This Cookbook is engineered as your one-stop reference to take your game AI programming to the next level. Get to grips with the essential building blocks of working with an agent, programming movement and navigation in a game environment, and improving your agent's decision making and coordination mechanisms - all through hands-on examples using easily customizable techniques. Discover how to emulate vision and hearing capabilities for your agent, for natural and humanlike AI behaviour, and improve them with the help of graphs. Empower your AI with decision-making functions through programming simple board games such as Tic-Tac-Toe and Checkers, and orchestrate agent coordination to get your AIs working together as one.

Who is this book for?

This book is intended for those who already have a basic knowledge of Unity and are eager to get more tools under their belt to solve AI and gameplay-related problems.

What you will learn

  • Use techniques such as Aand Ambush to empower your agents with path finding capabilities.
  • Create a representation of the world and make agents navigate it
  • Construct decision-making systems to make the agents take different actions
  • Make different agents coordinate actions and create the illusion of technical behavior
  • Simulate senses and apply them in an awareness system
  • Design and implement AI in board games such as Tic-Tac-Toe and Checkers
  • Implement efficient prediction mechanism in your agents with algorithms such as N-Gram predictor and naïve Bayes classifier
  • Understand and analyze how the influence maps work.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 31, 2016
Length: 278 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553587
Vendor :
Unity Technologies
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Mar 31, 2016
Length: 278 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553587
Vendor :
Unity Technologies
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 152.97
Unity 5.x Shaders and Effects Cookbook
$54.99
Unity 5.x Animation Cookbook
$48.99
Unity 5.x Game AI Programming Cookbook
$48.99
Total $ 152.97 Stars icon
Banner background image

Table of Contents

9 Chapters
1. Behaviors – Intelligent Movement Chevron down icon Chevron up icon
2. Navigation Chevron down icon Chevron up icon
3. Decision Making Chevron down icon Chevron up icon
4. Coordination and Tactics Chevron down icon Chevron up icon
5. Agent Awareness Chevron down icon Chevron up icon
6. Board Games AI Chevron down icon Chevron up icon
7. Learning Techniques Chevron down icon Chevron up icon
8. Miscellaneous Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8
(4 Ratings)
5 star 25%
4 star 0%
3 star 25%
2 star 25%
1 star 25%
Hugo Apr 28, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is really a Programming AI Cookbook, it is full of algorithms teaching how to create a game with AI, like in the book cover there is over than 70 recipes, this will enable you to achieve almost any kind of behavior that you want to implement, you will learn techniques from intelligent movement, navigation, avoid agents and walls, jump systems, decision making, find the shortest path, the list is very big, and you have to take a little time to understand the concepts, is good to have your Unity open with the book code examples to see the results, and most important try to implement your own behaviors based on the book, this way you can create new AI behaviors, learning with these examples you can create more professional games. I think this book is for people with at least a short experience working in Unity and C#, most of the book is implementing algorithms in code, the visual part is on the example code, but if you are a complete beginner this book can be good if you work hard to learn the basics on the other books like Learning C# in Unity and Unity 5 by example, or in the Unity documentation, tutorials and forum. As a cookbook I you recommend this book for anyone who work with game development in general, this is well written, have a great author and structure, can be a great tool to consult and design your game, If you have an idea and doesn't know where to start, I think that you can easily find here one recipe for a game mechanic to start prototyping your game, or to create a game feature during the game development or to create a post production, this book is a mind blow, you will start to have more ideas or you know where to start the ideas that you thought were more difficult before.
Amazon Verified review Amazon
Silverleaf Jul 28, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
I am a professional game developer and got this book because it seemed like a good reference to quickly glance at some boiler plate type code to get it up and running quickly in Unity for prototyping without a lot of fuss. While this book does serve pretty well in that capacity I also have a few gripes with it:1. There are a good deal of bugs I've found in the code and I've had to fix them (which is easy for me), BUT this is supposed to be a cookbook with supposedly already tested and stable code. Recipes shouldn't have runtime bugs that need to be fixed by the user before they will work correctly at all. Some of the code doesn't seem like it was ever even test run at all before publishing. As an example, I found several bugs in the A* code as well as the SetNeighbours() code in the get8 branch where that code has a basic bug that makes it only get 5 neighbors instead of the 8 it should be (the j loop was missing a + 1 on the max count). Then in addition to that, the same code can crash when indexing into the array using the 'c' value because based on the non-clamped values, the 'c' variable can become < 0 and causes an unhandled runtime exception. This is just one example of the types of issues I've run in to.2. I did not like that in order to find relevant code to one recipe, you have to thumb forward or backwards to other recipes you don't really care about in order to find missing method dependencies in the recipe you DO care about. This is a cookbook, but it reads more like one long tutorial spread over many sub-articles instead. It would have been better if all that code was maybe all put into a code index that was easily searchable by some tag id in the book like: Code Listing 1, etc. Instead I actually had to get manually 'search' other recipes and read them in order to track down missing code. :/3. The web link provided in the book for the GPWiki PriorityQueue is a dead link. The page doesn't even come up. So I had to just implement my own priority queue and shoehorn that in to the recipe code. (which was fun actually), but still, the book should make sure links on a book this new are actually valid?
Amazon Verified review Amazon
Amazon Customer Apr 05, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I found the code more confusing than helpful and somewhat disorganized. I've been coding AI most of my professional life (15+ yrs) and I found this book difficult to use. It might be okay as a book for beginners who don't really want to understand AI but just get something working, but I don't think it's even properly organized for that purpose. I'd recommend one of the Game AI Wisdom books or perhaps AI Game Programming Wisdom.
Amazon Verified review Amazon
Sparo Vigil & Mick Macha Mar 10, 2018
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Coming from a programming background in other fields and expecting a reasonable handbook to implementing AI in Unity, I have been disappointed in this book on multiple fronts. The author seems to have only a cursory understanding of C# programming (littering his code with unnecessary and obfuscating behavior like initializing structs to their default value), rarely discusses the actual meaning of his source code in detail, and goes so far as to reinvent the wheel on multiple occasions. As an example, he completely ignores Unity's built-in tools for managing state machines, in turn choosing to write a less capable one himself. All of chapter three is spent on that, which is roughly an eighth of the book, with no mention of Mecanim cover to cover.It is clear to me that he is simply unprepared to write a guide on this subject, let alone a cookbook. If you want to understand Unity, anything is better, inclusive of the on-site documentation. If you want to understand soft AI as applied to games, I might suggest Programming Game AI by Example, by Mat Buckland; it uses C++ instead of C#, but the descriptions are much clearer. If you need an actual cookbook, I would strongly suggest getting any other one, even if it requires a broader scope than Unity alone; it will still save you time.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.