Skip to content

Commit

Permalink
Adds projectile attacks to enemies
Browse files Browse the repository at this point in the history
  • Loading branch information
mnmaita committed Nov 16, 2023
1 parent 0ca82cf commit 1d39219
Showing 1 changed file with 47 additions and 3 deletions.
50 changes: 47 additions & 3 deletions src/game/enemy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,30 @@ use rand::seq::IteratorRandom;

use crate::{physics::Speed, playing};

use super::{combat::Range, BorderTile, Hitpoints, Player, TILE_SIZE};
use super::{
combat::{AttackDamage, AttackTimer, Range, SpawnProjectileEvent},
BorderTile, Hitpoints, Player, TILE_SIZE,
};

pub(super) struct EnemyPlugin;

impl Plugin for EnemyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(EnemySpawnTimer::new(3.));

app.add_systems(FixedUpdate, (spawn_enemies, move_enemies).run_if(playing()));
app.add_systems(
FixedUpdate,
(spawn_enemies, move_enemies, attack_player).run_if(playing()),
);
}
}

#[derive(Bundle)]
pub struct EnemyBundle {
pub marker: Enemy,
pub attack_damage: AttackDamage,
pub attack_timer: AttackTimer,
pub hitpoints: Hitpoints,
pub marker: Enemy,
pub range: Range,
pub speed: Speed,
pub sprite: SpriteBundle,
Expand Down Expand Up @@ -48,6 +56,8 @@ fn spawn_enemies(
let translation = tile_transform.translation.truncate().extend(1.);

commands.spawn(EnemyBundle {
attack_damage: AttackDamage(5),
attack_timer: AttackTimer(Timer::from_seconds(5., TimerMode::Repeating)),
hitpoints: Hitpoints::new(1),
marker: Enemy,
range: Range(TILE_SIZE.x * 3.),
Expand Down Expand Up @@ -82,3 +92,37 @@ fn move_enemies(
}
}
}

fn attack_player(
mut spawn_projectile_event_writer: EventWriter<SpawnProjectileEvent>,
mut enemy_query: Query<
(Entity, &Transform, &mut AttackTimer, &Range, &AttackDamage),
With<Enemy>,
>,
player_query: Query<&Transform, (With<Player>, Without<Enemy>)>,
time: Res<Time>,
) {
let player_transform = player_query.single();
let player_position = player_transform.translation.truncate();

for (enemy_entity, enemy_transform, mut enemy_attack_timer, enemy_range, enemy_attack_damage) in
&mut enemy_query
{
if enemy_attack_timer.tick(time.delta()).just_finished() {
let enemy_position = enemy_transform.translation.truncate();

if enemy_position.distance(player_position) <= enemy_range.0 {
let direction = (player_position - enemy_position).normalize();
let emitter = enemy_entity;

spawn_projectile_event_writer.send(SpawnProjectileEvent::new(
enemy_attack_damage.0,
direction,
emitter,
enemy_position,
1000.,
))
}
}
}
}

0 comments on commit 1d39219

Please sign in to comment.