Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 5.x Game AI Programming Cookbook

You're reading from   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
Product type Paperback
Published in Mar 2016
Publisher Packt
ISBN-13 9781783553570
Length 278 pages
Edition 1st Edition
Tools
Arrow right icon
Authors (2):
Arrow left icon
Jorge Palacios Jorge Palacios
Author Profile Icon Jorge Palacios
Jorge Palacios
Jorge Elieser P Garrido Jorge Elieser P Garrido
Author Profile Icon Jorge Elieser P Garrido
Jorge Elieser P Garrido
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Behaviors – Intelligent Movement FREE CHAPTER 2. Navigation 3. Decision Making 4. Coordination and Tactics 5. Agent Awareness 6. Board Games AI 7. Learning Techniques 8. Miscellaneous Index

Avoiding agents

In crowd-simulation games, it would be unnatural to see agents behaving entirely like particles in a physics-based system. The goal of this recipe is to create an agent capable of mimicking our peer-evasion movement.

Getting ready

We need to create a tag called Agent and assign it to those game objects that we would like to avoid, and we also need to have the Agent script component attached to them.

Getting ready

An example of how should look the Inspector of a dummy agent to avoid

How to do it...

This recipe will require the creation and handling of just one file:

  1. Create the AvoidAgent behavior, which is composed of a collision avoidance radius and the list of agents to avoid:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class AvoidAgent : AgentBehaviour
    {
        public float collisionRadius = 0.4f;
        GameObject[] targets;
    }
  2. Implement the Start function in order to set the list of agents according to the tag we created earlier:
    void Start ()
    {
        targets = GameObject.FindGameObjectsWithTag("Agent");
    }
  3. Define the GetSteering function:
    public override Steering GetSteering()
    {
        // body
    }
  4. Add the following variables to compute distances and velocities from agents that are nearby:
    Steering steering = new Steering();
    float shortestTime = Mathf.Infinity;
    GameObject firstTarget = null;
    float firstMinSeparation = 0.0f;
    float firstDistance = 0.0f;
    Vector3 firstRelativePos = Vector3.zero;
    Vector3 firstRelativeVel = Vector3.zero;
  5. Find the closest agent that is prone to collision with the current one:
    foreach (GameObject t in targets)
    {
        Vector3 relativePos;
        Agent targetAgent = t.GetComponent<Agent>();
        relativePos = t.transform.position - transform.position;
        Vector3 relativeVel = targetAgent.velocity - agent.velocity;
        float relativeSpeed = relativeVel.magnitude;
        float timeToCollision = Vector3.Dot(relativePos, relativeVel);
        timeToCollision /= relativeSpeed * relativeSpeed * -1;
        float distance = relativePos.magnitude;
        float minSeparation = distance - relativeSpeed * timeToCollision;
        if (minSeparation > 2 * collisionRadius)
            continue;
        if (timeToCollision > 0.0f && timeToCollision < shortestTime)
        {
            shortestTime = timeToCollision;
            firstTarget = t;
            firstMinSeparation = minSeparation;
            firstRelativePos = relativePos;
            firstRelativeVel = relativeVel;
        }
    }
  6. If there is one, then get away:
    if (firstTarget == null)
        return steering;
    if (firstMinSeparation <= 0.0f || firstDistance < 2 * collisionRadius)
        firstRelativePos = firstTarget.transform.position;
    else
        firstRelativePos += firstRelativeVel * shortestTime;
    firstRelativePos.Normalize();
    steering.linear = -firstRelativePos * agent.maxAccel;
    return steering;

How it works...

Given a list of agents, we take into consideration which one is closest, and if it is close enough, we make it so the agent tries to escape from the expected route of that first one according to its current velocity so that they don't collide.

There's more

This behavior works well when combined with other behaviors using blending techniques (some are included in this chapter); otherwise it's a starting point for your own collision avoidance algorithms.

You have been reading a chapter from
Unity 5.x Game AI Programming Cookbook
Published in: Mar 2016
Publisher: Packt
ISBN-13: 9781783553570
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime