Book Image

Unity 2018 Artificial Intelligence Cookbook - Second Edition

By : Jorge Palacios
Book Image

Unity 2018 Artificial Intelligence Cookbook - Second Edition

By: Jorge Palacios

Overview of this book

Interactive and engaging games come with intelligent enemies, and this intellectual behavior is combined with a variety of techniques collectively referred to as Artificial Intelligence. Exploring Unity's API, or its built-in features, allows limitless possibilities when it comes to creating your game's worlds and characters. This cookbook covers both essential and niche techniques to help you take your AI programming to the next level. To start with, you’ll quickly run through the essential building blocks of working with an agent, programming movement, and navigation in a game environment, followed by improving your agent's decision-making and coordination mechanisms – all through hands-on examples using easily customizable techniques. You’ll then discover how to emulate the vision and hearing capabilities of your agent for natural and humanlike AI behavior, and later improve the agents with the help of graphs. This book also covers the new navigational mesh with improved AI and pathfinding tools introduced in the Unity 2018 update. You’ll empower your AI with decision-making functions by programming simple board games, such as tic-tac-toe and checkers, and orchestrate agent coordination to get your AIs working together as one. By the end of this book, you’ll have gained expertise in AI programming and developed creative and interactive games.
Table of Contents (12 chapters)

Creating the behaviors template

Before creating our behaviors, we need to code the stepping stones that help us to create not only intelligent movement, but also help us to build a modular system to change and add these behaviors. We will create custom data types and base classes for most of the algorithms covered in this chapter.

Getting ready

Our first step is to remember the update functions' order of execution:

  • Update
  • LateUpdate

How to do it...

We need to create three classes, Steering, AgentBehaviour, and Agent:

  1. Steering serves as a custom data type for storing the movement and rotation of the agent:
using UnityEngine; 
public class Steering 
{ 
  public float angular; 
  public Vector3 linear; 
  public Steering () 
  { 
    angular = 0.0f; 
    linear = new Vector3(); 
  } 
} 
  1. AgentBehaviour is the template class for most of the behaviors covered in this chapter:
using UnityEngine; 
public class AgentBehaviour : MonoBehaviour 
{ 
  public GameObject target; 
  protected Agent agent; 
  public virtual void Awake () 
  { 
    agent = gameObject.GetComponent<Agent>(); 
  } 
  public virtual void Update () 
  { 
      agent.SetSteering(GetSteering()); 
  } 
  public virtual Steering GetSteering () 
  { 
    return new Steering(); 
  } 
} 
  1. Finally, Agent is the main component, and it makes use of behaviors in order to create intelligent movement. Create the file and its bare bones:
using UnityEngine; 
using System.Collections; 
public class Agent : MonoBehaviour 
{ 
    public float maxSpeed; 
    public float maxAccel; 
    public float orientation; 
    public float rotation; 
    public Vector3 velocity; 
    protected Steering steering; 
    void Start () 
    { 
        velocity = Vector3.zero; 
        steering = new Steering(); 
    } 
    public void SetSteering (Steering steering) 
    { 
        this.steering = steering; 
    } 
} 
  1. Next, we code the Update function, which handles the movement according to the current value:
public virtual void Update () 
{ 
    Vector3 displacement = velocity * Time.deltaTime; 
    orientation += rotation * Time.deltaTime; 
    // we need to limit the orientation values 
    // to be in the range (0 - 360) 
    if (orientation < 0.0f) 
        orientation += 360.0f; 
    else if (orientation > 360.0f) 
        orientation -= 360.0f; 
    transform.Translate(displacement, Space.World); 
    transform.rotation = new Quaternion(); 
    transform.Rotate(Vector3.up, orientation); 
} 
  1. Finally, we implement the LateUpdate function, which takes care of updating the steering for the next frame according to the current frame's calculations:
public virtual void LateUpdate () 
{ 
    velocity += steering.linear * Time.deltaTime; 
    rotation += steering.angular * Time.deltaTime; 
    if (velocity.magnitude > maxSpeed) 
    { 
        velocity.Normalize(); 
        velocity = velocity * maxSpeed; 
    } 
    if (steering.angular == 0.0f) 
    { 
        rotation = 0.0f; 
    } 
    if (steering.linear.sqrMagnitude == 0.0f) 
    { 
        velocity = Vector3.zero; 
    } 
    steering = new Steering(); 
} 

How it works...

The idea is to be able to delegate the movement's logic inside the GetSteering() function on the behaviors that we will later build, simplifying our agent's class to a main calculation based on those.

Besides, we are guaranteed to be able to set the agent's steering value before it is used thanks to Unity script and function execution orders.

There's more...

This is a component-based approach, which means that we must remember to always have an Agent script attached to GameObject for the behaviors to work as expected.

See also