我正在实施一种简单的分离转向算法(用于轴对齐的2D矩形)。 算法:
最后,在总矢量的相反方向上施加力(加速度),并且每帧都更新矩形位置。
这是分离逻辑:
bool Cell::seperateFrom(CellsContainer& cells) {
Vector2D force_sum;
int neighbor_count = 0;
for (auto& other : cells) {
if (!(*this == other) && this->overlaps(other)) {
Vector2D position_diff = this->position - other.position;
//normalize
position_diff /= (float)sqrt(std::pow(position_diff.x,2) + std::pow(position_diff.y,2));
force_sum += position_diff;
neighbor_count++;
}
}
if (neighbor_count > 0) {
// calculate steer away vector;
Vector2D steering = force_sum - this->velocity;
//normalize
steering /= (float) sqrt(std::pow(steering.x,2) + std::pow(steering.y,2));
//move by tile size units
steering *= static_cast<float> (TILE_SIZE);
this->addForce(steering);
return true;
} else {
// not overlapping, stop moving
this->velocity *= 0.0f;
return false;
}
}
我从紧密排列的随机生成的矩形开始,看起来分离正在工作,但结果是非常有方向性的,并且矩形大小不均匀(如下所示),我不明白为什么。
编辑:
updatePosition函数:
void Cell::updatePosition() {
this->velocity += this->acceleration;
this->position += this->velocity;
this->rectangle.setPosition(this->position);
this->acceleration *= 0.0f;
}
addForce:
void addForce(const Vector2D& force) {this->acceleration += force;}
主循环:
void main_loop(WindowType& window, CellsContainer& cells) {
while (true) {
window.clear();
for (auto& cell_obj : cells) {
cell_obj.seperateFrom(cells);
cell_obj.updatePosition();
window.draw(cell_obj.getRectangle());
}
window.display();
}
}