From 95cdd904850476b0d3d92226f6b6b4594eef614f Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Wed, 10 Jul 2024 14:03:38 -0500 Subject: [PATCH] Fix over-application of cohesion forces The cohesion function was erroneously applying forces to boids that shouldn't be experiencing them. It shouldn't be iterating over all boids-with-velocity and adding speed. It should be applying that force only to the one boid that the loop is examining at that iteration. I also cleaned up the signature to have just one query struct. I had it split as two because I was getting issues with mutability. The fix was to make the query mutable, and then keep the Transforms as immutable references. This way I can reach through and update the Velocity alone. --- src/birdoids_plugin.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/birdoids_plugin.rs b/src/birdoids_plugin.rs index 5c96f63b..671e9be8 100644 --- a/src/birdoids_plugin.rs +++ b/src/birdoids_plugin.rs @@ -9,8 +9,8 @@ const BACKGROUND_COLOR: Color = Color::srgb(0.4, 0.4, 0.4); const PLAYERBOID_COLOR: Color = Color::srgb(1.0, 0.0, 0.0); const TURN_FACTOR: f32 = 1.; const BOID_VIEW_RANGE: f32 = 50.0; -const COHESION_FACTOR: f32 = 0.1; -const SEPARATION_FACTOR: f32 = 0.05; +const COHESION_FACTOR: f32 = 1.0; +const SEPARATION_FACTOR: f32 = 0.1; pub struct BoidsPlugin; @@ -168,10 +168,9 @@ fn check_keyboard( fn cohesion( spatial_tree: Res>, - boids: Query<&Transform, With>, - mut velocities: Query<&mut Velocity, With>, + mut boids: Query<(&Transform, &mut Velocity), With>, ) { - for transform in &boids { + for (transform, mut velocity) in &mut boids { let neighbors = spatial_tree.within_distance( transform.translation.xy(), BOID_VIEW_RANGE @@ -180,11 +179,9 @@ fn cohesion( let center_of_mass = neighbors.iter() .map(|(pos, _opt_entity)| pos ) .sum::() / neighbors.len() as f32; - - for mut velocity in &mut velocities { - let towards = (center_of_mass - transform.translation.xy()).normalize(); - **velocity += towards.extend(0.0) * COHESION_FACTOR; - } + + let towards = (center_of_mass - transform.translation.xy()).normalize(); + **velocity += towards.extend(0.0) * COHESION_FACTOR; } } } @@ -200,7 +197,7 @@ fn separation( for (boid_transform, mut boid_acceleration) in &mut boids { let neighbors = spatial_tree.within_distance( boid_transform.translation.xy(), - BOID_VIEW_RANGE, + BOID_VIEW_RANGE / 4.0, ); let accel = neighbors.iter() .map(|(pos, _)| pos.extend(0.0))