我正在查看一些用于boids的伪代码并用 C++ 编写。但是,我发现 boid 偶尔会相互碰撞。考虑到伪代码的简单程度,我认为我已经正确编程了它。然而,当我显示所有 boid 的位置时,其中一些具有相同的坐标。
链接中的伪代码:
PROCEDURE rule2(boid bJ)
Vector c = 0;
FOR EACH BOID b
IF b != bJ THEN
IF |b.position - bJ.position| < 100 THEN
c = c - (b.position - bJ.position)
END IF
END IF
END
RETURN c
END PROCEDURE
我的代码是:
std::pair <signed int, signed int> keep_distance(std::vector <Boid> & boids, Boid & boid){
signed int dx = 0;
signed int dy = 0;
for(Boid & b : boids){
if (boid != b){ // this checks an "id" number, not location
if (b.dist(boid) < MIN_DIST){
dx -= b.get_x() - boid.get_x();
dy -= b.get_y() - boid.get_y();
}
}
}
return std::pair <signed int, signed int> (dx, dy);
}
和
MIN_DIST = 100;
unsigned int Boid::dist(const Boid & b){
return (unsigned int) sqrt((b.x - x) * (b.x - x) + (b.y - y) * (b.y - y));
}
唯一的主要区别是这两个代码之间的区别应该是,而不是vector c
,我使用组件来代替。
我用来移动每个 boid 的函数顺序是:
center_of_mass(boids, new_boids[i]); // rule 1
match_velocity(boids, new_boids[i]); // rule 3
keep_within_bound(new_boids[i]);
tendency_towards_place(new_boids[i], mouse_x, mouse_y);
keep_distance(boids, new_boids[i]); // rule 2
有什么明显的我没有看到吗?也许我做错了一些愚蠢的向量算术?