Book Image

Unity Artificial Intelligence Programming - Fifth Edition

By : Dr. Davide Aversa
Book Image

Unity Artificial Intelligence Programming - Fifth Edition

By: Dr. Davide Aversa

Overview of this book

Developing artificial intelligence (AI) for game characters in Unity has never been easier. Unity provides game and app developers with a variety of tools to implement AI, from 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 game worlds and characters. The updated fifth edition of Unity Artificial Intelligence Programming starts by breaking down AI into simple concepts. 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. As you progress, you’ll learn how to implement a finite state machine (FSM) to determine how your AI behaves, apply probability and randomness to make games less predictable, and implement a basic sensory system. Later, you’ll understand how to set up a game map with a navigation mesh, incorporate movement through techniques such as A* pathfinding, and provide characters with decision-making abilities using behavior trees. By the end of this Unity book, you’ll have the skills you need to bring together all the concepts and practical lessons you’ve learned to build an impressive vehicle battle game.
Table of Contents (17 chapters)
1
Part 1:Basic AI
6
Part 2:Movement and Navigation
11
Part 3:Advanced AI

Using a simple FSM for the enemy tank AI

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

You can find the source code in the SimpleFSM.cs file:

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 = FSMState.Patrol;
    //Speed of the tank
    private float curSpeed = 150.0f;
    //Tank Rotation Speed
    private float curRotSpeed = 2.0f;
    //Bullet
    public GameObject Bullet;
    //Whether the NPC is destroyed or not
    private...