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

Getting ready

We need a couple of basic behaviors called Seek and Flee; place them right after the Agent class in the scripts' execution order.

The following is the code for the Seek behavior:

using UnityEngine; 
using System.Collections; 
public class Seek : AgentBehaviour 
{ 
    public override Steering GetSteering() 
    { 
        Steering steering = new Steering(); 
        steering.linear = target.transform.position - transform.position; 
        steering.linear.Normalize(); 
        steering.linear = steering.linear * agent.maxAccel; 
        return steering; 
    } 
} 

Also, we need to implement the Flee behavior:

using UnityEngine; 
using System.Collections; 
public class Flee : AgentBehaviour 
{ 
    public override Steering GetSteering() 
    { 
        Steering steering = new Steering(); 
        steering.linear = transform.position - target.transform.position; 
        steering.linear.Normalize(); 
        steering.linear = steering.linear * agent.maxAccel; 
        return steering; 
    } 
}