在自治智能体的实现过程中,我们给对象注入了生命。
个体一般会和其它个体一起存在,并且相互影响。因此,我i们的目的不仅仅是模拟个体的行为,还应该把小车放入一个由许多个体组成的系统中,让它们相互影响。
复杂系统的三个主要原则:
- 个体之间存在小范围的联系。
- 个体的动作是并行的。如每个个体都应该移动,并绘制它们的外形。
- 系统在整体上会呈现一种自发现象。个体之间的交互会出现复杂行为和智能模式(蚁群、迁移、地震、雪花等)
群集有3个规则:
- 分离(又叫“躲避”) :避免与邻居发生碰撞
- 对齐(又叫“复制”):转向力的方向与邻居保持一致
- 聚集(又叫“集中”):朝着邻居的中心转向
分离算法:
// 分离
// 检查邻近对象并施加力的行为
PVector separate (ArrayList<Boid> boids) {
// 期望分离距离
float desiredseparation = 25.0f;
PVector steer = new PVector(0,0,0);
int count = 0;
// 遍历
for (Boid other : boids) {
float d = PVector.dist(position,other.position);
// 距离大于0且小于期望分离距离(距离为0为自己)
if ((d > 0) && (d < desiredseparation)) {
// 指向邻居的向量
PVector diff = PVector.sub(position,other.position);
// 向量归一化
diff.normalize();
// 向量的大小与距离成反比
diff.div(d);
// 转向力叠加
steer.add(diff);
// 记录满足条件的对象数量
count++;
}
}
若满足条件的对象存在
//if (count > 0) {
// steer.div((float)count);
//}
if (steer.mag() > 0) {
// Reynolds: 转向力 = 期望速度 - 当前速度
steer.normalize();
steer.mult(maxspeed);
steer.sub(velocity);
steer.limit(maxforce);
}
return steer;
}
对齐算法:
// 对齐
// 检查该对象附近的对象,计算平均速度
PVector align (ArrayList<Boid> boids) {
float neighbordist = 50;
PVector sum = new PVector(0,0);
int count = 0;
for (Boid other : boids) {
float d = PVector.dist(position,other.position);
if ((d > 0) && (d <