分离(Separation)行为
分离行为的作用是使角色与周围其他角色保持一定的距离,这样可以避免多个角色相互挤到一起。当分离行为应用在许多AI角色(如鸟群中的鸟)上时,它们将会向四周散开,尽可能拉开距离。
C#脚本代码
using UnityEngine;
namespace AI.Steering
{
/// <summary>
/// 分散
/// </summary>
public class SteeringForDisperse : Steering
{
//字段
//雷达
public Radar radar = new Radar();
//与中心点距离最近的距离
public float nearDistance;
//方法
public override Vector3 GetForce()
{
//通过雷达扫描得到周围邻居,算出 与所有邻居产生的排斥力总和
var allNeighbour = radar.SanNeighbours(transform.position);
expectForce = Vector3.zero;
//算出 与所有邻居产生的排斥力总和
for (int i = 0; i < allNeighbour.Length; i++)
{
var dir = transform.position - allNeighbour[i].transform.position;
if (dir.magnitude < nearDistance && gameObject != allNeighbour[i].gameObject)
{
expectForce += dir.normalized;
}
}
if (expectForce == Vector3.zero) return Vector3.zero;
expectForce = expectForce.normalized * speed;
return (expectForce - vehicle.currentForce) * weight;
}
}
}
测试:
- 创建多个Cube物体。
- 并把所有的Cube物体的标签设置为neighbour
- 赋给所有Cube物体LocomotionController脚本和SteeringForDisperse脚本。
- 运行
运行:
观察多个Cube运行轨迹。