use bevy::prelude::*;
use crate::chunk::Chunk;
use crate::player::{Player, PlayerHealth};
use crate::voxel::VoxelType;
use crate::world::ChunkManager;
use crate::world::collision::resolve_capsule_collision;
pub const MOB_HALF_HEIGHT: f32 = 0.5;
pub const MOB_RADIUS: f32 = 0.35;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MobAiState {
Patrol,
Chase,
Attack,
}
#[derive(Component)]
pub struct Mob {
pub health: f32,
pub ai_state: MobAiState,
pub velocity: Vec3,
pub vertical_velocity: f32,
pub on_ground: bool,
pub attack_cooldown: f32,
pub patrol_timer: f32,
pub patrol_dir: Vec3,
pub home_position: Vec3,
}
#[derive(Clone, Debug)]
pub struct MobConfig {
pub max_health: f32,
pub chase_speed: f32,
pub patrol_speed: f32,
pub detection_radius: f32,
pub attack_range: f32,
pub attack_damage: f32,
pub attack_cooldown: f32,
pub patrol_radius: f32,
pub despawn_distance: f32,
pub gravity: Option<f32>,
pub color: Color,
}
impl Default for MobConfig {
fn default() -> Self {
Self {
max_health: 20.0,
chase_speed: 3.5,
patrol_speed: 1.2,
detection_radius: 12.0,
attack_range: 1.5,
attack_damage: 4.0,
attack_cooldown: 1.2,
patrol_radius: 6.0,
despawn_distance: 64.0,
gravity: Some(20.0),
color: Color::srgb(0.6, 0.1, 0.1),
}
}
}
#[derive(bevy::ecs::message::Message, Debug, Clone)]
pub struct MobDied {
pub position: Vec3,
}
pub fn spawn_mob(
position: Vec3,
config: MobConfig,
commands: &mut Commands,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
) -> Entity {
let mesh = meshes.add(Cuboid::new(
MOB_RADIUS * 2.0,
(MOB_HALF_HEIGHT + MOB_RADIUS) * 2.0,
MOB_RADIUS * 2.0,
));
let material = materials.add(StandardMaterial {
base_color: config.color,
..default()
});
commands
.spawn((
Mob {
health: config.max_health,
ai_state: MobAiState::Patrol,
velocity: Vec3::ZERO,
vertical_velocity: 0.0,
on_ground: false,
attack_cooldown: 0.0,
patrol_timer: 0.0,
patrol_dir: Vec3::ZERO,
home_position: position,
},
MobConfigComponent(config),
Transform::from_translation(position),
Visibility::default(),
Mesh3d(mesh),
MeshMaterial3d(material),
))
.id()
}
#[derive(Component)]
pub struct MobConfigComponent(pub MobConfig);
fn mob_ai_system(
player_q: Query<&Transform, With<Player>>,
mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
time: Res<Time>,
) {
let Ok(player_tf) = player_q.single() else {
return;
};
let player_pos = player_tf.translation;
let dt = time.delta_secs();
for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
let mob_pos = mob_tf.translation;
let dist = mob_pos.distance(player_pos);
let config = &cfg.0;
mob.attack_cooldown = (mob.attack_cooldown - dt).max(0.0);
mob.patrol_timer += dt;
match mob.ai_state {
MobAiState::Patrol => {
if dist < config.detection_radius {
mob.ai_state = MobAiState::Chase;
} else {
if mob.patrol_timer > 3.0 {
mob.patrol_timer = 0.0;
let t = mob_pos.x * 13.7 + mob_pos.z * 7.3 + time.elapsed_secs() * 2.3;
mob.patrol_dir = Vec3::new(t.sin(), 0.0, t.cos()).normalize_or_zero();
if mob_pos.distance(mob.home_position) > config.patrol_radius {
let home_dir = (mob.home_position - mob_pos).normalize_or_zero();
mob.patrol_dir = Vec3::new(home_dir.x, 0.0, home_dir.z);
}
}
mob.velocity = mob.patrol_dir * config.patrol_speed;
}
}
MobAiState::Chase => {
if dist > config.detection_radius * 1.5 {
mob.ai_state = MobAiState::Patrol;
mob.patrol_dir = Vec3::ZERO;
} else if dist < config.attack_range {
mob.ai_state = MobAiState::Attack;
mob.velocity = Vec3::ZERO;
} else {
let dir = (player_pos - mob_pos).normalize_or_zero();
mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * config.chase_speed;
}
}
MobAiState::Attack => {
if dist > config.attack_range * 1.5 {
mob.ai_state = MobAiState::Chase;
}
let dir = (player_pos - mob_pos).normalize_or_zero();
mob.velocity = Vec3::new(dir.x, 0.0, dir.z) * (config.chase_speed * 0.3);
}
}
}
}
fn mob_attack_system(
player_q: Query<&Transform, With<Player>>,
mut mob_q: Query<(&Transform, &mut Mob, &MobConfigComponent)>,
mut player_health: ResMut<PlayerHealth>,
) {
let Ok(player_tf) = player_q.single() else {
return;
};
let player_pos = player_tf.translation;
for (mob_tf, mut mob, cfg) in mob_q.iter_mut() {
if mob.ai_state != MobAiState::Attack {
continue;
}
if mob.attack_cooldown > 0.0 {
continue;
}
let dist = mob_tf.translation.distance(player_pos);
if dist <= cfg.0.attack_range {
player_health.health = (player_health.health - cfg.0.attack_damage).max(0.0);
mob.attack_cooldown = cfg.0.attack_cooldown;
}
}
}
fn mob_physics_system<V: VoxelType>(
mut mob_q: Query<(&mut Transform, &mut Mob, &MobConfigComponent)>,
manager: Res<ChunkManager>,
chunks: Query<&Chunk<V>>,
time: Res<Time>,
) {
let dt = time.delta_secs();
for (mut tf, mut mob, cfg) in mob_q.iter_mut() {
match cfg.0.gravity {
Some(g) => {
if !mob.on_ground {
mob.vertical_velocity -= g * dt;
}
let move_delta = (mob.velocity + Vec3::Y * mob.vertical_velocity) * dt;
tf.translation += move_delta;
let half = MOB_HALF_HEIGHT;
let bottom = tf.translation - Vec3::Y * half;
let top = tf.translation + Vec3::Y * half;
let push =
resolve_capsule_collision::<V, ()>(bottom, top, MOB_RADIUS, &manager, &chunks);
tf.translation += push;
if push.y > 0.01 {
mob.on_ground = true;
mob.vertical_velocity = 0.0;
} else {
mob.on_ground = false;
}
}
None => {
mob.vertical_velocity = 0.0;
mob.on_ground = false;
let move_delta = mob.velocity * dt;
tf.translation += move_delta;
let half = MOB_HALF_HEIGHT;
let bottom = tf.translation - Vec3::Y * half;
let top = tf.translation + Vec3::Y * half;
let push =
resolve_capsule_collision::<V, ()>(bottom, top, MOB_RADIUS, &manager, &chunks);
tf.translation += push;
}
}
}
}
fn mob_death_system(
mob_q: Query<(Entity, &Transform, &Mob)>,
mut commands: Commands,
mut died_writer: bevy::ecs::message::MessageWriter<MobDied>,
) {
for (entity, tf, mob) in mob_q.iter() {
if mob.health <= 0.0 {
died_writer.write(MobDied {
position: tf.translation,
});
commands.entity(entity).despawn();
}
}
}
fn mob_despawn_system(
mob_q: Query<(Entity, &Transform, &MobConfigComponent)>,
player_q: Query<&Transform, With<Player>>,
mut commands: Commands,
) {
let Ok(player_tf) = player_q.single() else {
return;
};
let player_pos = player_tf.translation;
for (entity, tf, cfg) in mob_q.iter() {
if tf.translation.distance(player_pos) > cfg.0.despawn_distance {
commands.entity(entity).despawn();
}
}
}
pub struct MobPlugin<V: VoxelType> {
_m: std::marker::PhantomData<V>,
}
impl<V: VoxelType> MobPlugin<V> {
pub fn new() -> Self {
Self {
_m: std::marker::PhantomData,
}
}
}
impl<V: VoxelType> Default for MobPlugin<V> {
fn default() -> Self {
Self::new()
}
}
impl<V: VoxelType> Plugin for MobPlugin<V> {
fn build(&self, app: &mut App) {
app.add_message::<MobDied>();
app.add_systems(
Update,
(
mob_ai_system,
mob_attack_system,
mob_physics_system::<V>,
mob_death_system,
mob_despawn_system,
),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn step(mob: &mut Mob, tf: &mut Transform, gravity: Option<f32>, dt: f32) {
match gravity {
Some(g) => {
if !mob.on_ground {
mob.vertical_velocity -= g * dt;
}
let move_delta = (mob.velocity + Vec3::Y * mob.vertical_velocity) * dt;
tf.translation += move_delta;
mob.on_ground = false;
}
None => {
mob.vertical_velocity = 0.0;
mob.on_ground = false;
tf.translation += mob.velocity * dt;
}
}
}
fn make_mob(velocity: Vec3) -> Mob {
Mob {
health: 20.0,
ai_state: MobAiState::Patrol,
velocity,
vertical_velocity: 0.0,
on_ground: false,
attack_cooldown: 0.0,
patrol_timer: 0.0,
patrol_dir: Vec3::ZERO,
home_position: Vec3::ZERO,
}
}
#[test]
fn mob_default_has_gravity_enabled() {
assert_eq!(MobConfig::default().gravity, Some(20.0));
}
#[test]
fn mob_zero_gravity_does_not_fall() {
let mut mob = make_mob(Vec3::ZERO);
let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
for _ in 0..100 {
step(&mut mob, &mut tf, None, 0.1);
}
assert_eq!(tf.translation.y, 100.0, "zero-g mob must not fall");
assert_eq!(mob.vertical_velocity, 0.0);
assert!(!mob.on_ground);
}
#[test]
fn mob_zero_gravity_drifts_with_velocity() {
let mut mob = make_mob(Vec3::new(2.0, 0.0, 0.0));
let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
for _ in 0..10 {
step(&mut mob, &mut tf, None, 0.1);
}
assert!(
(tf.translation.x - 2.0).abs() < 1e-4,
"x drift = {}",
tf.translation.x
);
assert_eq!(tf.translation.y, 100.0, "y must not change in zero-g");
}
#[test]
fn mob_with_gravity_falls() {
let mut mob = make_mob(Vec3::ZERO);
let mut tf = Transform::from_translation(Vec3::new(0.0, 100.0, 0.0));
for _ in 0..10 {
step(&mut mob, &mut tf, Some(20.0), 0.1);
}
assert!(
tf.translation.y < 100.0,
"grounded mob must fall (got y={})",
tf.translation.y
);
assert!(
mob.vertical_velocity < 0.0,
"vertical velocity must accumulate downward"
);
}
}