Skip to content

Commit

Permalink
Update PlayerAttackTimer and add collision reaction
Browse files Browse the repository at this point in the history
  • Loading branch information
PurityLake committed Dec 11, 2023
1 parent b6e3f00 commit a8ac944
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions src/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,22 @@ struct PlayerAttackTimer {
impl Default for PlayerAttackTimer {
fn default() -> Self {
Self {
timer: Timer::new(Duration::from_secs_f32(0.75), TimerMode::Once),
timer: Timer::new(Duration::from_secs_f32(0.8), TimerMode::Once),
attacked: false,
}
}
}

#[derive(Component, Default)]
struct PlayerAttack;
#[derive(Component)]
struct PlayerAttack {
pub health: i32,
}

impl Default for PlayerAttack {
fn default() -> Self {
Self { health: 10 }
}
}

#[derive(Resource, Default)]
pub struct PlayerAttackSprite {
Expand Down Expand Up @@ -71,6 +79,7 @@ impl Plugin for PlayerPlugin {
change_player_anim,
update_attack,
tick_attack_timer,
react_to_collision,
)
.run_if(in_state(GameState::GamePlay)),
);
Expand Down Expand Up @@ -232,7 +241,7 @@ fn handle_input(
visibility: Visibility::Visible,
..default()
},
PlayerAttack,
PlayerAttack::default(),
RigidBody::KinematicPositionBased,
Collider::capsule_y(10.0, 6.0),
Sensor,
Expand Down Expand Up @@ -261,3 +270,29 @@ fn update_attack(
}
}
}

fn react_to_collision(
mut commands: Commands,
mut collision_events: EventReader<CollisionEvent>,
mut query: Query<(Entity, &mut PlayerAttack)>,
) {
for event in collision_events.read() {
if let CollisionEvent::Started(a, b, flags) = event {
if flags.bits() & 0b01 == 0b01 {
let attack = if let Ok(result) = query.get_mut(*a) {
Ok(result)
} else if let Ok(result) = query.get_mut(*b) {
Ok(result)
} else {
Err(())
};
if let Ok((entity, mut attack)) = attack {
attack.health -= 1;
if attack.health <= 0 {
commands.entity(entity).despawn();
}
}
}
}
}
}

0 comments on commit a8ac944

Please sign in to comment.