Border avoidance system

This commit is contained in:
2024-07-08 16:10:31 -05:00
parent 7224199a94
commit 8f52ad3954

View File

@@ -3,6 +3,7 @@ use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
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.;
pub struct BoidsPlugin;
@@ -13,6 +14,7 @@ impl Plugin for BoidsPlugin{
.add_systems(Startup, (spawn_camera, spawn_boids))
.add_systems(FixedUpdate, (
apply_velocity,
turn_if_edge,
check_keyboard,
));
}
@@ -82,6 +84,31 @@ fn spawn_boids(
));
}
fn turn_if_edge(
mut query: Query<(&mut Transform, &mut Velocity), With<Boid>>,
window: Query<&Window>,
) {
if let Ok(window) = window.get_single() {
let (width, height) = (window.resolution.width(), window.resolution.height());
for (transform, mut velocity) in &mut query {
let boid_pos = transform.translation.xy();
if boid_pos.x <= -width / 2. + 50. {
velocity.x += TURN_FACTOR;
} else if boid_pos.x >= width / 2. - 50. {
velocity.x -= TURN_FACTOR;
}
if boid_pos.y <= -height / 2. + 50. {
velocity.y += TURN_FACTOR;
} else if boid_pos.y >= height / 2. - 50. {
velocity.y -= TURN_FACTOR;
}
}
} else {
panic!("System turn_if_edge(...) got an Err(_) when getting the window properties");
}
}
fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
for (mut transform, velocity) in &mut query {
let delta_position = **velocity * time.delta_seconds();