聚集(Cohesion)行为
聚集行为产生一个使AI角色移向邻居的质心的操控力,这个操控力使得多个AI角色聚集到了一起。
迭代所有邻居,求AI角色平均值,然后利用靠近行为,将平均值作为目标。
C#脚本代码
using UnityEngine;
namespace AI.Steering
{
/// <summary>
/// 聚集
/// </summary>
public class SteeringForCollect : Steering
{
//字段
//雷达
public Radar radar = new Radar();
//与中心点距离最近的距离
public float nearDistance;
//方法
public override Vector3 GetForce()
{
//通过雷达扫描得到周围邻居,算出所有邻居中心点
var allNeighbour = radar.SanNeighbours(transform.position);
var center = Vector3.zero;
for(int i = 0; i < allNeighbour.Length; i++)
{
center += allNeighbour[i].transform.position;
}
center = center / allNeighbour.Length;
//向中心靠近
if (Vector3.Distance(center, transform.position) > nearDistance)
{
expectForce = (center - transform.position).normalized * speed;
return (expectForce - vehicle.currentForce) * weight;
}
return Vector3.zero;
}
}
}
测试:
- 创建多个Cube物体。
- 并把所有的Cube物体的标签设置为neighbour
- 赋给所有Cube物体LocomotionController脚本和SteeringForCollect脚本。
- 运行
运行:
观察多个Cube运行轨迹。