New separation rule function

This commit is contained in:
2025-09-03 14:07:34 -05:00
parent 7b380196a5
commit 451311126d

View File

@@ -166,24 +166,32 @@ fn cohesion(
fn separation( fn separation(
spatial_tree: Res<KDTree2<TrackedByKdTree>>, spatial_tree: Res<KDTree2<TrackedByKdTree>>,
mut boids: Query<(&Transform, &mut Force), With<Boid>>, mut boids: Query<(Entity, &Transform, &mut Force), With<Boid>>,
) { ) {
// for each boid // for each boid
// find neighbors // find neighbors
// sum force from neighbors // sum force from neighbors
// apply force // apply force
for (boid_transform, mut boid_acceleration) in &mut boids { for (this_entt, tsfm, mut force) in &mut boids {
let neighbors = let impulse = spatial_tree
spatial_tree.within_distance(boid_transform.translation.xy(), BOID_VIEW_RANGE / 4.0); .within_distance(tsfm.translation.xy(), BOID_VIEW_RANGE / 8.0)
let accel = neighbors.iter().map(|(pos, _)| pos.extend(0.0)).fold( .iter()
Vec3::ZERO, .filter_map(|(pos, entt)| {
|accumulator, neighbor| { // Skip self-comparison. A boid should not try to separate from itself.
let force = separation_force(boid_transform.translation.xy(), neighbor.xy()) let entt = entt
.unwrap_or_default(); .expect("within_distance gave me an entity... with no entity ID... somehow");
accumulator + *force * SEPARATION_FACTOR if this_entt == entt {
}, None
); } else {
boid_acceleration.0 += accel; Some(pos.extend(0.0))
}
})
.fold(Vec3::ZERO, |acc, other| {
// let force = tsfm.translation - other;
let force = separation_force(tsfm.translation.xy(), other.xy()).expect("angy");
acc + force.0
});
force.0 += impulse * SEPARATION_FACTOR;
} }
} }