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

How to do it...

Now, we need to make some changes to the Agent class:

  1. Add a new namespace from the library:
using System.Collections.Generic; 
  1. Add the member variable for the minimum steering value to consider a group of behaviors:
public float priorityThreshold = 0.2f; 
  1. Add the member variable for holding the group of behavior results:
private Dictionary<int, List<Steering>> groups; 
  1. Initialize the variable in the Start function:
groups = new Dictionary<int, List<Steering>>(); 
  1. Modify the LateUpdate function so that the steering variable is set by calling GetPrioritySteering:
public virtual void LateUpdate () 
{ 
    //  funnelled steering through priorities 
    steering = GetPrioritySteering(); 
    groups.Clear(); 
    // ... the rest of the computations stay the same 
    steering = new Steering(); 
} 
  1. Modify the SetSteering function's signature and definition to store the steering values in their corresponding priority groups:
public void SetSteering (Steering steering, int priority) 
{ 
    if (!groups.ContainsKey(priority)) 
    { 
        groups.Add(priority, new List<Steering>()); 
    } 
    groups[priority].Add(steering); 
} 
  1. Finally, implement the GetPrioritySteering function to funnel the steering group:
private Steering GetPrioritySteering () 
{ 
    Steering steering = new Steering(); 
    float sqrThreshold = priorityThreshold * priorityThreshold; 
    foreach (List<Steering> group in groups.Values) 
    { 
        steering = new Steering(); 
        foreach (Steering singleSteering in group) 
        { 
            steering.linear += singleSteering.linear; 
            steering.angular += singleSteering.angular; 
        } 
        if (steering.linear.sqrMagnitude > sqrThreshold || 
                Mathf.Abs(steering.angular) > priorityThreshold) 
        { 
            return steering; 
        } 
    } 
    return steering; 
}