Skip to content

Commit

Permalink
Bounce!
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-blackbird committed Jul 17, 2022
1 parent d4f8f88 commit 101d2d4
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions examples/games/contributors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ struct Velocity {
rotation: f32,
}

const GRAVITY: f32 = -9.821 * 100.0;
const GRAVITY: f32 = 9.821 * 100.0;
const SPRITE_SIZE: f32 = 75.0;

const SATURATION_DESELECTED: f32 = 0.3;
Expand Down Expand Up @@ -243,7 +243,7 @@ fn velocity_system(time: Res<Time>, mut velocity_query: Query<&mut Velocity>) {
let delta = time.delta_seconds();

for mut velocity in &mut velocity_query {
velocity.translation += Vec3::new(0.0, GRAVITY * delta, 0.0);
velocity.translation.y -= GRAVITY * delta;
}
}

Expand All @@ -256,16 +256,24 @@ fn collision_system(
windows: Res<Windows>,
mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>,
) {
let mut rng = rand::thread_rng();

let window = windows.primary();
let window = if let Some(window) = windows.get_primary() {
window
} else {
println!("The window was closed. Bye!");
return;
};

let ceiling = window.height() / 2.;
let ground = -(window.height() / 2.);

let wall_left = -(window.width() / 2.);
let wall_right = window.width() / 2.;

// The maximum height the birbs should try to reach is one birb below the top of the window.
let max_bounce_height = window.height() - SPRITE_SIZE * 2.0;

let mut rng = rand::thread_rng();

for (mut velocity, mut transform) in &mut query {
let left = transform.translation.x - SPRITE_SIZE / 2.0;
let right = transform.translation.x + SPRITE_SIZE / 2.0;
Expand All @@ -275,11 +283,16 @@ fn collision_system(
// clamp the translation to not go out of the bounds
if bottom < ground {
transform.translation.y = ground + SPRITE_SIZE / 2.0;
// apply an impulse upwards
velocity.translation.y = rng.gen_range(700.0..1000.0);

// How high this birb will bounce.
let bounce_height = rng.gen_range((max_bounce_height * 0.4)..max_bounce_height);

// Apply the velocity that would bounce the birb up to bounce_height.
velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt();
}
if top > ceiling {
transform.translation.y = ceiling - SPRITE_SIZE / 2.0;
velocity.translation.y *= -1.0;
}
// on side walls flip the horizontal velocity
if left < wall_left {
Expand Down

0 comments on commit 101d2d4

Please sign in to comment.