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

How to do it...

They use the same approach, but in terms of implementation, the name of the member variables change, as well as some computations in the first half of the GetSteering function:

  1. First, implement the Arrive behavior with its member variables to define the radius for stopping (target) and slowing down:
using UnityEngine; 
using System.Collections; 
 
public class Arrive : AgentBehaviour 
{ 
    public float targetRadius; 
    public float slowRadius; 
    public float timeToTarget = 0.1f; 
} 
  1. Create the GetSteering function:
public override Steering GetSteering() 
{ 
    // code in next steps 
} 
  1. Define the first half of the GetSteering function, in which we compute the desired speed depending on the distance from the target according to the radii variables:
Steering steering = new Steering(); 
Vector3 direction = target.transform.position - transform.position; 
float distance = direction.magnitude; 
float targetSpeed; 
if (distance < targetRadius) 
    return steering; 
if (distance > slowRadius) 
    targetSpeed = agent.maxSpeed; 
else 
    targetSpeed = agent.maxSpeed * distance / slowRadius; 
  1. Define the second half of the GetSteering function, in which we set the steering value and clamp it according to the maximum speed:
Vector3 desiredVelocity = direction; 
desiredVelocity.Normalize(); 
desiredVelocity *= targetSpeed; 
steering.linear = desiredVelocity - agent.velocity; 
steering.linear /= timeToTarget; 
if (steering.linear.magnitude > agent.maxAccel) 
{ 
    steering.linear.Normalize(); 
    steering.linear *= agent.maxAccel; 
} 
return steering; 
  1. To implement Leave, change the name of the member variables:
using UnityEngine; 
using System.Collections; 
 
public class Leave : AgentBehaviour 
{ 
    public float escapeRadius; 
    public float dangerRadius; 
    public float timeToTarget = 0.1f; 
} 
  1. Define the first half of the GetSteering function:
Steering steering = new Steering(); 
Vector3 direction = transform.position - target.transform.position; 
float distance = direction.magnitude; 
if (distance > dangerRadius) 
    return steering; 
float reduce; 
if (distance < escapeRadius) 
    reduce = 0f; 
else 
    reduce = distance / dangerRadius * agent.maxSpeed; 
float targetSpeed = agent.maxSpeed - reduce; 
  1. And finally, the second half of GetSteering stays just the same.