cargo fmt

main
Elijah Voigt 3 months ago
parent fe4708d52d
commit 86375aef0a

@ -2,12 +2,12 @@ use games::*;
fn main() { fn main() {
App::new() App::new()
.add_plugins(( .add_plugins((BaseGamePlugin {
BaseGamePlugin {
name: "2d game example".into(), name: "2d game example".into(),
game_type: GameType::Two, game_type: GameType::Two,
}, },))
)).add_systems(Startup, spawn_guy).run(); .add_systems(Startup, spawn_guy)
.run();
} }
fn spawn_guy( fn spawn_guy(
@ -29,4 +29,3 @@ fn spawn_guy(
commands.spawn((name, material, mesh, t)); commands.spawn((name, material, mesh, t));
} }

@ -22,14 +22,18 @@ impl Default for BaseGamePlugin {
impl Plugin for BaseGamePlugin { impl Plugin for BaseGamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins(DefaultPlugins.set(WindowPlugin { app.add_plugins(
DefaultPlugins
.set(WindowPlugin {
primary_window: Some(Window { primary_window: Some(Window {
fit_canvas_to_parent: true, fit_canvas_to_parent: true,
canvas: Some(format!("#{}-canvas", self.name)), canvas: Some(format!("#{}-canvas", self.name)),
..default() ..default()
}), }),
..default() ..default()
}).set(ImagePlugin::default_nearest())) })
.set(ImagePlugin::default_nearest()),
)
.add_plugins(DebuggingPlugin) .add_plugins(DebuggingPlugin)
.add_plugins(MeshPickingPlugin) .add_plugins(MeshPickingPlugin)
.add_plugins(LoadingPlugin) .add_plugins(LoadingPlugin)

@ -75,7 +75,7 @@ fn main() {
sync_resource_to_ui::<Deaths>.run_if(resource_changed::<Deaths>), sync_resource_to_ui::<Deaths>.run_if(resource_changed::<Deaths>),
sync_resource_to_ui::<RewindFrames>.run_if(resource_changed::<RewindFrames>), sync_resource_to_ui::<RewindFrames>.run_if(resource_changed::<RewindFrames>),
), ),
scoring.run_if(on_event::<CollisionEnded>) scoring.run_if(on_event::<CollisionEnded>),
), ),
) )
.add_observer(flap) .add_observer(flap)
@ -137,7 +137,16 @@ fn init_bird(
let tape = Tape::default(); let tape = Tape::default();
commands.spawn((name, mesh, material, physics, t, Bird, tape, CollisionEventsEnabled)); commands.spawn((
name,
mesh,
material,
physics,
t,
Bird,
tape,
CollisionEventsEnabled,
));
} }
#[derive(Component, Clone)] #[derive(Component, Clone)]
@ -187,14 +196,15 @@ fn init_obstacles(
) )
}; };
let hitbox = { let hitbox = {
let physics = (RigidBody::Static, Collider::rectangle(1.0, 10.0), Sensor, CollisionEventsEnabled); let physics = (
RigidBody::Static,
Collider::rectangle(1.0, 10.0),
Sensor,
CollisionEventsEnabled,
);
let name = Name::new("hitbox"); let name = Name::new("hitbox");
( (name.clone(), physics.clone(), Hitbox)
name.clone(),
physics.clone(),
Hitbox,
)
}; };
// TODO: Instead of spawning infinite floor/pipes, we should instead spawn enough for 1-3 a few // TODO: Instead of spawning infinite floor/pipes, we should instead spawn enough for 1-3 a few
@ -203,16 +213,20 @@ fn init_obstacles(
// overhead fairly static. // overhead fairly static.
(1..10).for_each(|i| { (1..10).for_each(|i| {
// TODO: Jitter up/down/close/far of pipes for challenge // TODO: Jitter up/down/close/far of pipes for challenge
let above = Transform::from_xyz(300.0 * i as f32, 300.0, -1.0).with_scale(Vec3::splat(100.0)); let above =
Transform::from_xyz(300.0 * i as f32, 300.0, -1.0).with_scale(Vec3::splat(100.0));
commands.spawn((pipe.clone(), above)); commands.spawn((pipe.clone(), above));
let below = Transform::from_xyz(300.0 * i as f32, -200.0, -1.0).with_scale(Vec3::splat(100.0)); let below =
Transform::from_xyz(300.0 * i as f32, -200.0, -1.0).with_scale(Vec3::splat(100.0));
commands.spawn((pipe.clone(), below)); commands.spawn((pipe.clone(), below));
let hitbox_pos = Transform::from_xyz(300.0 * i as f32, 0.0, 10.0).with_scale(Vec3::splat(100.0)); let hitbox_pos =
Transform::from_xyz(300.0 * i as f32, 0.0, 10.0).with_scale(Vec3::splat(100.0));
commands.spawn((hitbox_pos, hitbox.clone())); commands.spawn((hitbox_pos, hitbox.clone()));
let floor = Transform::from_xyz(300.0 * i as f32, -300.0, 1.0).with_scale(Vec3::splat(100.0)); let floor =
Transform::from_xyz(300.0 * i as f32, -300.0, 1.0).with_scale(Vec3::splat(100.0));
commands.spawn((ground.clone(), floor)); commands.spawn((ground.clone(), floor));
}); });
} }
@ -227,12 +241,34 @@ fn init_ui(mut commands: Commands) {
}, },
PlayerState::Stasis, PlayerState::Stasis,
children![ children![
(Text::new("You Died"), TextLayout::new_with_justify(JustifyText::Center)), (
(SyncResource::<Score>::default(), Text::default(), TextLayout::new_with_justify(JustifyText::Center)), Text::new("You Died"),
(SyncResource::<Flaps>::default(), Text::default(), TextLayout::new_with_justify(JustifyText::Center)), TextLayout::new_with_justify(JustifyText::Center)
(SyncResource::<RewindFrames>::default(), Text::default(), TextLayout::new_with_justify(JustifyText::Center)), ),
(SyncResource::<Deaths>::default(), Text::default(), TextLayout::new_with_justify(JustifyText::Center)), (
(Text::new("Press R to Rewind"), TextLayout::new_with_justify(JustifyText::Center)), SyncResource::<Score>::default(),
Text::default(),
TextLayout::new_with_justify(JustifyText::Center)
),
(
SyncResource::<Flaps>::default(),
Text::default(),
TextLayout::new_with_justify(JustifyText::Center)
),
(
SyncResource::<RewindFrames>::default(),
Text::default(),
TextLayout::new_with_justify(JustifyText::Center)
),
(
SyncResource::<Deaths>::default(),
Text::default(),
TextLayout::new_with_justify(JustifyText::Center)
),
(
Text::new("Press R to Rewind"),
TextLayout::new_with_justify(JustifyText::Center)
),
], ],
)); ));
@ -255,19 +291,17 @@ fn init_ui(mut commands: Commands) {
)) ))
.observe(start_game); .observe(start_game);
commands.spawn( commands
Node { .spawn(Node {
align_self: AlignSelf::End, align_self: AlignSelf::End,
justify_self: JustifySelf::Center, justify_self: JustifySelf::Center,
flex_direction: FlexDirection::Row, flex_direction: FlexDirection::Row,
..default() ..default()
}, })
).with_children(|parent| { .with_children(|parent| {
parent parent
.spawn(( .spawn((
Node { Node { ..default() },
..default()
},
Button, Button,
children![Text::new("Rewind!"),], children![Text::new("Rewind!"),],
)) ))
@ -275,13 +309,7 @@ fn init_ui(mut commands: Commands) {
.observe(end_rewind); .observe(end_rewind);
parent parent
.spawn(( .spawn((Node { ..default() }, Button, children![Text::new("Flap!"),]))
Node {
..default()
},
Button,
children![Text::new("Flap!"),],
))
.observe(flap_button); .observe(flap_button);
}); });
@ -294,7 +322,7 @@ fn init_ui(mut commands: Commands) {
BackgroundColor(WHITE.into()), BackgroundColor(WHITE.into()),
SyncResource::<Score>::default(), SyncResource::<Score>::default(),
Text::default(), Text::default(),
TextLayout::new_with_justify(JustifyText::Center) TextLayout::new_with_justify(JustifyText::Center),
)); ));
} }
@ -306,7 +334,11 @@ fn end_rewind(_trigger: Trigger<Pointer<Released>>, mut next: ResMut<NextState<P
next.set(PlayerState::Alive); next.set(PlayerState::Alive);
} }
fn flap_button(trigger: Trigger<Pointer<Pressed>>, mut commands: Commands, bird: Single<Entity, With<Bird>>) { fn flap_button(
trigger: Trigger<Pointer<Pressed>>,
mut commands: Commands,
bird: Single<Entity, With<Bird>>,
) {
let e = *bird; let e = *bird;
info!("Flapping {:?}", e); info!("Flapping {:?}", e);
commands.trigger_targets(Flap, e); commands.trigger_targets(Flap, e);
@ -328,7 +360,8 @@ fn un_pause_game(mut next: ResMut<NextState<PlayerState>>) {
struct Flap; struct Flap;
// Observer for flapping // Observer for flapping
fn flap(trigger: Trigger<Flap>, fn flap(
trigger: Trigger<Flap>,
mut bird: Query<&mut ExternalImpulse, With<Bird>>, mut bird: Query<&mut ExternalImpulse, With<Bird>>,
mut flaps: ResMut<Flaps>, mut flaps: ResMut<Flaps>,
) { ) {
@ -387,7 +420,9 @@ fn record(
"Only record in the alive state" "Only record in the alive state"
); );
birds.iter_mut().for_each(|(transform, linear_velocity, angular_velocity, mut tape)| { birds
.iter_mut()
.for_each(|(transform, linear_velocity, angular_velocity, mut tape)| {
tape.translations.push(transform.translation); tape.translations.push(transform.translation);
tape.rotations.push(transform.rotation); tape.rotations.push(transform.rotation);
tape.linear_velocities.push(*linear_velocity); tape.linear_velocities.push(*linear_velocity);
@ -397,7 +432,15 @@ fn record(
fn rewind( fn rewind(
#[cfg(debug_assertions)] state: Res<State<PlayerState>>, #[cfg(debug_assertions)] state: Res<State<PlayerState>>,
mut birds: Query<(&mut Transform, &mut AngularVelocity, &mut LinearVelocity, &mut Tape), With<Bird>>, mut birds: Query<
(
&mut Transform,
&mut AngularVelocity,
&mut LinearVelocity,
&mut Tape,
),
With<Bird>,
>,
mut frames: ResMut<RewindFrames>, mut frames: ResMut<RewindFrames>,
) { ) {
debug_assert!( debug_assert!(
@ -405,13 +448,14 @@ fn rewind(
"Only rewind in the rewinding state" "Only rewind in the rewinding state"
); );
birds.iter_mut().for_each(|(mut transform, mut angular_velocity, mut linear_velocity, mut tape)| { birds.iter_mut().for_each(
|(mut transform, mut angular_velocity, mut linear_velocity, mut tape)| {
match (tape.translations.pop(), tape.rotations.pop()) { match (tape.translations.pop(), tape.rotations.pop()) {
(Some(t), Some(r)) => { (Some(t), Some(r)) => {
transform.translation = t; transform.translation = t;
transform.rotation = r; transform.rotation = r;
frames.0 += 1; frames.0 += 1;
}, }
(None, None) => (), (None, None) => (),
_ => panic!("Translations and rotations are out of sync!"), _ => panic!("Translations and rotations are out of sync!"),
} }
@ -422,7 +466,8 @@ fn rewind(
if let Some(lv) = tape.linear_velocities.pop() { if let Some(lv) = tape.linear_velocities.pop() {
*linear_velocity = lv; *linear_velocity = lv;
} }
}); },
);
} }
// PERF: May run more than necessary, should be event-driven on aabb intersection // PERF: May run more than necessary, should be event-driven on aabb intersection
@ -523,9 +568,10 @@ fn scoring(
hitboxes: Query<Entity, With<Hitbox>>, hitboxes: Query<Entity, With<Hitbox>>,
mut score: ResMut<Score>, mut score: ResMut<Score>,
) { ) {
events.read().filter(|CollisionEnded(a, b)| { events
bird.contains(*a) && hitboxes.contains(*b) .read()
}).for_each(|_| { .filter(|CollisionEnded(a, b)| bird.contains(*a) && hitboxes.contains(*b))
.for_each(|_| {
info!("Hit event while {:?}", state.get()); info!("Hit event while {:?}", state.get());
match state.get() { match state.get() {
PlayerState::Alive => score.0 = score.0.saturating_add(1), PlayerState::Alive => score.0 = score.0.saturating_add(1),
@ -533,5 +579,4 @@ fn scoring(
PlayerState::Pause | PlayerState::Stasis => (), PlayerState::Pause | PlayerState::Stasis => (),
} }
}) })
} }

@ -6,7 +6,8 @@ pub struct Physics2dPlugin;
impl Plugin for Physics2dPlugin { impl Plugin for Physics2dPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default())).add_systems( app.add_plugins((PhysicsPlugins::default(), PhysicsDebugPlugin::default()))
.add_systems(
Update, Update,
toggle_physics_debug_render.run_if(state_changed::<DebuggingState>), toggle_physics_debug_render.run_if(state_changed::<DebuggingState>),
); );

Loading…
Cancel
Save