From dca8bcdaa7e546ec91c9a91d14717db573598346 Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Wed, 3 Sep 2025 14:19:57 -0500 Subject: [PATCH] Add speed_controller to maintain system energy The starting velocities going outwards in a circle means that the sum of energy in the system is 0. As the boids come back together, they will slow down to fall into a lattice. This is interesting, but not the flocking behavior Boids are supposed to have. I've replaced the `space_brakes` function with this new speed controller to keep boids moving between two speeds. Anything too slow will speed up along it's current vector, and anything too fast will slow down. --- src/birdoids/mod.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/birdoids/mod.rs b/src/birdoids/mod.rs index 5b84965c..a0a4a642 100644 --- a/src/birdoids/mod.rs +++ b/src/birdoids/mod.rs @@ -10,11 +10,13 @@ use crate::birdoids::physics::{apply_velocity, Force, Velocity}; 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.0; -const BOID_VIEW_RANGE: f32 = 50.0; +const BOID_VIEW_RANGE: f32 = 15.0; const COHESION_FACTOR: f32 = 1.0; -const SEPARATION_FACTOR: f32 = 1.0; -const ALIGNMENT_FACTOR: f32 = 10.0; -const SPACEBRAKES_COEFFICIENT: f32 = 0.01; +const SEPARATION_FACTOR: f32 = 10.0; +const ALIGNMENT_FACTOR: f32 = 1.0; +const SPACEBRAKES_COEFFICIENT: f32 = 0.5; +const LOW_SPEED_THRESHOLD: f32 = 50.0; +const HIGH_SPEED_THRESHOLD: f32 = 200.0; pub struct BoidsPlugin; @@ -37,7 +39,7 @@ impl Plugin for BoidsPlugin { cohesion, separation, alignment, - // space_brakes, + speed_controller, ), ); } @@ -85,10 +87,16 @@ fn spawn_boids( )); } -fn space_brakes(mut mobs: Query<&mut Force, With>) { - for mut accel in &mut mobs { - let braking_dir = -accel.0 * SPACEBRAKES_COEFFICIENT; - accel.0 += braking_dir; +/// Controls the boid's minimum and maximum speed according to a low- and +/// high-threshold. Boids moving too slow are sped up, and boids moving too +/// fast are slowed down. +fn speed_controller(mut mobs: Query<(&Velocity, &mut Force), With>) { + for (vel, mut impulse) in &mut mobs { + if vel.0.length() < LOW_SPEED_THRESHOLD { + impulse.0 += vel.0 * SPACEBRAKES_COEFFICIENT; + } else if vel.0.length() > HIGH_SPEED_THRESHOLD { + impulse.0 += -vel.0 * SPACEBRAKES_COEFFICIENT; + } } }