Unity 2018 Artificial Intelligence Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

How to do it...

Pursue and Evade are essentially the same algorithm, but differ in terms of the base class they derive from:

  1. Create the Pursue class, derived from Seek, and add the attributes for the prediction:
using UnityEngine; 
using System.Collections; 
 
public class Pursue : Seek 
{ 
    public float maxPrediction; 
    private GameObject targetAux; 
    private Agent targetAgent; 
} 
  1. Implement the Awake function in order to set up everything according to the real target:
public override void Awake() { base.Awake(); targetAgent = target.GetComponent<Agent>(); targetAux = target; target = new GameObject(); } 
  1. Implement the OnDestroy function for properly handling the internal object:
void OnDestroy () 
{ 
    Destroy(targetAux); 
} 
  1. Implement the GetSteering function:
public override Steering GetSteering() 
{ 
    Vector3 direction = targetAux.transform.position - transform.position; 
    float distance = direction.magnitude; 
    float speed = agent.velocity.magnitude; 
    float prediction; 
    if (speed <= distance / maxPrediction) 
        prediction = maxPrediction; 
    else 
        prediction = distance / speed; 
    target.transform.position = targetAux.transform.position; 
    target.transform.position += targetAgent.velocity * prediction; 
    return base.GetSteering(); 
} 
  1. To create the Evade behavior, the procedure is just the same, but it takes into account the fact that Flee is the parent class:
public class Evade : Flee 
{ 
    // everything stays the same 
}