Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Unity Artificial Intelligence Programming
Unity Artificial Intelligence Programming

Unity Artificial Intelligence Programming: Add powerful, believable, and fun AI entities in your game with the power of Unity 2018! , Fourth Edition

Arrow left icon
Profile Icon Dr. Davide Aversa Profile Icon Peters Profile Icon Aung Sithu Kyaw
Arrow right icon
€8.99 €26.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook Nov 2018 246 pages 4th Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Dr. Davide Aversa Profile Icon Peters Profile Icon Aung Sithu Kyaw
Arrow right icon
€8.99 €26.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (3 Ratings)
eBook Nov 2018 246 pages 4th Edition
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.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 Artificial Intelligence Programming

Finite State Machines

In this chapter, we'll learn how to implement a Finite State Machine (FSM) in a Unity3D game by studying the simple tank game-mechanic example that comes with this book.

In our game, the player controls a tank. The enemy tanks move around the scene, following four waypoints. Once the player's tank enters the vision range of the enemy tanks, they will start chasing it; then, once they are close enough to attack, they'll start shooting at our player's tank.

To control the AI of our enemy tanks, we use FSM. First, we'll use simple switch statements to implement our tank AI states, then we'll use an FSM framework based on and adapted from the C# FSM framework that can be found at http://wiki.unity3d.com/index.php?title=Finite_State_Machine.

The topics we will be covering in this chapter are the following:

  • The player's tank
  • ...

The player's tank

Before writing the script for our player's tank, let's take a look at how we set up the PlayerTank game object. Our Tank object is a simple Mesh with the Rigidbody and Box Collider components. The Tank object is composed of two separate meshes, Tank and Turret, such that Turret is a child of Tank. This structure allows for the independent rotation of the Turret object using the mouse movement and, at the same time, will follow automatically the Tank body wherever it goes. Then, we create an empty game object for our SpawnPoint transform. We use it as a reference position point when shooting a bullet. Finally, for the player's Tank, we need to assign the Player tag to our Tank object. Now let's take a look at the controller class:

Our tank entity

The player's Tank is controlled by the PlayerTankController class. We are using the...

The Bullet class

Next, we set up our Bullet prefab with two orthogonal planes using a laser-like material and a Particles/Additive property in the Shader field:

Our Bullet prefab

The code in the Bullet.cs file is as follows:

using UnityEngine; 
using System.Collections; 
 
public class Bullet : MonoBehaviour 
{ 
    //Explosion Effect
[SerializeField] private GameObject Explosion;
[SerializeField]
private float Speed = 600.0f;
[SerializeField]
private float LifeTime = 3.0f;

public int damage = 50; void Start() { Destroy(gameObject, LifeTime); } void Update() { transform.position += transform.forward * Speed * Time.deltaTime; } void OnCollisionEnter(Collision collision) { ContactPoint contact = collision.contacts[0]; Instantiate(Explosion, contact.point, Quaternion...

Setting up waypoints

Next, we will put four Cube game objects at random places. They represent waypoints inside our scene and, therefore, we name them WandarPoints:

WandarPoints

Here is what our WandarPoint object will look like:

WanderPoint properties

Note that we need to tag those points with a tag called WandarPoint. Later, we use this tag when we try to find the waypoints from our tank AI. As you can see in its properties, a waypoint is just a Cube game object with the Mesh Renderer checkbox disabled, and the Box Collider object removed.

We can select the gizmo icon by clicking the small arrow near the object's name in the inspector

We could even use an empty object with a gizmo icon since all we need from a waypoint is its position and the transformation data. However, we're using the Cube objects here so that waypoints are easier to visualize.

...

The abstract FSM class

Next, we implement a generic abstract class to define the methods that our enemy tank AI class has to implement.

The code in the FSM.cs file is as follows:

using UnityEngine; 
using System.Collections; 
 
public class FSM : MonoBehaviour  
{ 
    //Player Transform 
    protected Transform playerTransform; 
 
    //Next destination position of the NPC Tank 
    protected Vector3 destPos; 
 
    //List of points for patrolling 
    protected GameObject[] pointList; 
 
    //Bullet shooting rate 
    protected float shootRate; 
    protected float elapsedTime; 
 
    //Tank Turret 
    public Transform turret { get; set; } 
    public Transform bulletSpawnPoint { get; set; } 
 
    protected virtual void Initialize() { } 
    protected virtual void FSMUpdate() { } 
    protected virtual void FSMFixedUpdate() { } 
 
    // Use this for initialization 
    void...

The enemy tank AI

Let's look at the real code for our AI tanks. Let's create a new class, called SimpleFSM, which inherits from our FSM abstract class.

The code in the SimpleFSM.cs file is as follows:

using UnityEngine; 
using System.Collections; 
 
public class SimpleFSM : FSM  
{ 
 
    public enum FSMState 
    { 
      None, 
      Patrol, 
      Chase, 
      Attack, 
      Dead, 
    } 
 
    //Current state that the NPC is reaching 
    public FSMState curState; 
 
    //Speed of the tank 
    private float curSpeed; 
 
    //Tank Rotation Speed 
    private float curRotSpeed; 
 
    //Bullet 
[SerializeField] private GameObject Bullet; //Whether the NPC is destroyed or not private bool bDead; private int health;

// We overwrite the deprecated built-in `rigidbody` variable.
new private Rigidbody rigidbody;

Here, we declare a few...

Using an FSM framework

The FSM framework we're going to use here is adapted from the C# FSM framework, which can be found at https://wiki.unity3d.com/index.php?title=Finite_State_Machine. That framework is again a part of the Deterministic Finite State Machine framework, based on Chapter 3.1 of Game Programming Gems 1, by Eric Dybsend. We'll only be looking at the differences between this FSM and the one we made earlier. The complete FSM can be found with the assets that come with the book. We'll now study how the framework works and how we can use it to implement our tank AI.

AdvanceFSM and FSMState are the two main classes of our framework. Let's take a look at them first.

The AdvanceFSM class

The AdvanceFSM...

Summary

In this chapter, we learned how to implement state machines in Unity3D based on a simple tank game. We first looked at how to implement FSM in the most direct way by using the switch statements. Then we studied how to use a framework to make the AI implementation easier to manage and extend.

In the next chapter, we will take a look at randomness and probability, and see how we can use it to make the outcome of our games more unpredictable.

Left arrow icon Right arrow icon

Key benefits

  • Build richer games by learning the essential concepts in AI for games like Behavior Trees and Navigation Meshes
  • Implement character behaviors and simulations using the Unity Machine Learning toolkit
  • Explore the latest Unity 2018 features to make implementation of AI in your game easier

Description

Developing Artificial Intelligence (AI) for game characters in Unity 2018 has never been easier. Unity provides game and app developers with a variety of tools to implement AI, from the basic techniques to cutting-edge machine learning-powered agents. 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 fourth edition with Unity will help you break down AI 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. Further on, you'll learn how 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'll then learn how to implement simple ?ocks and crowd dynamics, which are key AI concepts in Unity. Moving on, you'll learn how to implement a behavior tree through a game-focused example. Lastly, you'll apply all the concepts in the book to build a popular game.

Who is this book 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.

What you will learn

  • Create smarter game worlds and characters with C# programming
  • Apply automated character movement using pathfinding and steering behaviors
  • Implement non-player character decision-making algorithms using Behavior Trees and FSMs
  • Build believable and highly efficient artificial flocks and crowds
  • Create sensory systems for your AI with the most commonly used techniques
  • Construct decision-making systems to make agents take different actions
  • Explore the application of machine learning in Unity

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2018
Length: 246 pages
Edition : 4th
Language : English
ISBN-13 : 9781789531459
Vendor :
Unity Technologies
Languages :
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 : Nov 30, 2018
Length: 246 pages
Edition : 4th
Language : English
ISBN-13 : 9781789531459
Vendor :
Unity Technologies
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 115.97
Unity 2018 Artificial Intelligence Cookbook
€36.99
Unity Artificial Intelligence Programming
€32.99
Unity 2018 Cookbook
€45.99
Total 115.97 Stars icon
Banner background image

Table of Contents

12 Chapters
Introduction to AI Chevron down icon Chevron up icon
Finite State Machines Chevron down icon Chevron up icon
Randomness and Probability Chevron down icon Chevron up icon
Implementing Sensors Chevron down icon Chevron up icon
Flocking Chevron down icon Chevron up icon
Path-Following and Steering Behaviors Chevron down icon Chevron up icon
A* Pathfinding Chevron down icon Chevron up icon
Navigation Mesh Chevron down icon Chevron up icon
Behavior Trees Chevron down icon Chevron up icon
Machine Learning in Unity Chevron down icon Chevron up icon
Putting It All Together Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(3 Ratings)
5 star 33.3%
4 star 66.7%
3 star 0%
2 star 0%
1 star 0%
RhoneRanger Jan 31, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
When I received this book, I read it through once and thought to myself, "Wow, this book is really thorough" and I decided to read it through again, but much closer. Not only are the author an excellent writers, but good coders as as well. They take the reader on a journey and explain each topic thoroughly and delightfully as you learn the concepts of state machines, path finding, behaviors and much much more. This book has everything you need to know for AI game programming, and is a must have for any game programming library.
Amazon Verified review Amazon
Rus Kuzmin Nov 12, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I'm 50/50 about this book as for the price I was expecting more (£30)..Don't get me wrong, examples in the book are good but they are a very basic overview of the topics; good for beginners but no one else. There just isn't much detail and it only address' the most common topics.If you're looking for a beginners guide to AI (In Unity), get this book. If you are looking for detail, theory and more in-depth examples, look else where.
Amazon Verified review Amazon
Mike Aug 19, 2020
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
A good introduction. Sometimes could use a bigger variety of examples and there are some mistakes. Overall a good read.
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.