add coranth moving towards target and post-attack event

This commit is contained in:
Jim 2025-08-28 08:34:40 -04:00
parent e9790f156d
commit 1f8ecf9a9e
Signed by: jim
GPG key ID: 3236D2F059A7C0AC
15 changed files with 249 additions and 58 deletions

25
Cargo.lock generated
View file

@ -1801,6 +1801,7 @@ dependencies = [
name = "combat" name = "combat"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"avian3d",
"bevy", "bevy",
"state", "state",
] ]
@ -1963,6 +1964,8 @@ dependencies = [
"camera", "camera",
"combat", "combat",
"combat_damagers", "combat_damagers",
"inhabitant",
"inhabitant_coranth",
"input", "input",
"level", "level",
"physics", "physics",
@ -2846,6 +2849,27 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a" checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
[[package]]
name = "inhabitant"
version = "0.1.0"
dependencies = [
"bevy",
"combat",
]
[[package]]
name = "inhabitant_coranth"
version = "0.1.0"
dependencies = [
"avian3d",
"bevy",
"building",
"combat",
"combat_damagers",
"inhabitant",
"state",
]
[[package]] [[package]]
name = "inotify" name = "inotify"
version = "0.11.0" version = "0.11.0"
@ -3000,6 +3024,7 @@ dependencies = [
"building_impaler", "building_impaler",
"camera", "camera",
"combat", "combat",
"inhabitant_coranth",
"state", "state",
] ]

View file

@ -47,4 +47,6 @@ building_core = { path = "crates/building_core" }
building = { path = "crates/building" } building = { path = "crates/building" }
building_impaler = { path = "crates/building_impaler" } building_impaler = { path = "crates/building_impaler" }
combat_damagers = { path = "crates/combat_damagers" } combat_damagers = { path = "crates/combat_damagers" }
inhabitant = { path = "crates/inhabitant" }
inhabitant_coranth = { path = "crates/inhabitant_coranth" }
#new internal crates go here #new internal crates go here

View file

@ -1,7 +1,7 @@
( (
map: { map: {
MouseButton(Left): [ MouseMovementY: [
CameraPanEnable, CameraPanY,
], ],
MouseScroll: [ MouseScroll: [
CameraZoom, CameraZoom,
@ -10,14 +10,14 @@
CameraYaw, CameraYaw,
CameraPanX, CameraPanX,
], ],
MouseMovementY: [ KeyCode(Escape): [
CameraPanY, TogglePause,
], ],
MouseButton(Middle): [ MouseButton(Middle): [
CameraOrbitEnable, CameraOrbitEnable,
], ],
KeyCode(Escape): [ MouseButton(Left): [
TogglePause, CameraPanEnable,
], ],
KeyCode(F1): [ KeyCode(F1): [
ToggleDebugUI, ToggleDebugUI,

View file

@ -3,7 +3,7 @@
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use bevy::prelude::*; use bevy::prelude::*;
use combat::Health; use combat::{Health, Team};
pub struct BuildingPlugin; pub struct BuildingPlugin;
@ -12,7 +12,7 @@ impl Plugin for BuildingPlugin {
} }
#[derive(Component, Default)] #[derive(Component, Default)]
#[require(Health)] #[require(Health, Team::Core)]
pub struct Building { pub struct Building {
pub level: u32, pub level: u32,
} }

View file

@ -5,6 +5,7 @@ edition = "2024"
[dependencies] [dependencies]
bevy = { workspace = true } bevy = { workspace = true }
avian3d = { workspace = true }
state = { path = "../state" } state = { path = "../state" }

View file

@ -4,6 +4,7 @@
use std::time::Duration; use std::time::Duration;
use avian3d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use state::GameSystemSet; use state::GameSystemSet;
@ -16,14 +17,25 @@ impl Plugin for CombatPlugin {
.add_systems( .add_systems(
FixedUpdate, FixedUpdate,
tick_invulnerability.in_set(GameSystemSet::StatusEffects), tick_invulnerability.in_set(GameSystemSet::StatusEffects),
); )
.register_type::<Team>();
} }
} }
#[derive(Component, Clone, Debug, PartialEq, Eq)] #[derive(PhysicsLayer, Default, Component, Clone, Debug, PartialEq, Eq, Reflect)]
pub enum Team { pub enum Team {
#[default]
Core, Core,
Immune, Inhabitant,
}
impl Team {
pub fn collision_layers(&self) -> CollisionLayers {
match self {
Team::Core => CollisionLayers::new(Team::Core, LayerMask::ALL),
Team::Inhabitant => CollisionLayers::new(Team::Inhabitant, LayerMask::ALL),
}
}
} }
#[derive(Event, Debug, Default)] #[derive(Event, Debug, Default)]
@ -33,6 +45,13 @@ pub struct Attacked {
pub skip_invulnerability: bool, pub skip_invulnerability: bool,
} }
#[derive(Event, Debug)]
pub struct GaveDamage {
pub target: Entity,
pub amount: f32,
pub skip_invulnerability: bool,
}
#[derive(Event, Debug)] #[derive(Event, Debug)]
pub struct Died { pub struct Died {
pub slayer: Option<Entity>, pub slayer: Option<Entity>,
@ -133,12 +152,12 @@ fn on_attack(
&& let Some(team) = opt_team && let Some(team) = opt_team
&& team == attacker_team && team == attacker_team
{ {
info!("avoiding friendly fire!");
return; return;
} }
let defense = opt_defense.cloned().unwrap_or_default(); let defense = opt_defense.cloned().unwrap_or_default();
let damage_taken = defense.calc_damage(trigger.event().amount); let damage_taken = defense.calc_damage(trigger.event().amount);
health.current = (health.current - damage_taken).max(0.0); let old_health = health.current;
health.current = (old_health - damage_taken).max(0.0);
info!( info!(
"{:?} attacked {:?} for {} damage. New health = {}", "{:?} attacked {:?} for {} damage. New health = {}",
trigger trigger
@ -150,6 +169,16 @@ fn on_attack(
damage_taken, damage_taken,
health.current health.current
); );
if let Some(attacker) = trigger.event().attacker {
commands.trigger_targets(
GaveDamage {
target: trigger.target(),
amount: old_health - health.current,
skip_invulnerability: trigger.event().skip_invulnerability,
},
attacker,
);
}
if let Ok(mut ec) = commands.get_entity(trigger.target()) { if let Ok(mut ec) = commands.get_entity(trigger.target()) {
if health.current <= 0. { if health.current <= 0. {
ec.trigger(Died { ec.trigger(Died {

View file

@ -30,7 +30,6 @@ fn deal_contact_damage(
mut commands: Commands, mut commands: Commands,
) { ) {
for event in reader.read() { for event in reader.read() {
info!("event recv!");
if let Ok(contact) = query.get(event.0) { if let Ok(contact) = query.get(event.0) {
commands.trigger_targets( commands.trigger_targets(
Attacked { Attacked {

View file

@ -0,0 +1,11 @@
[package]
name = "inhabitant"
version = "0.1.0"
edition = "2024"
[dependencies]
bevy = { workspace = true }
combat = { path = "../combat" }
[lints]
workspace = true

View file

@ -0,0 +1,16 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use bevy::prelude::*;
use combat::{Health, Team};
pub struct InhabitantPlugin;
impl Plugin for InhabitantPlugin {
fn build(&self, _app: &mut App) {}
}
#[derive(Component, Default)]
#[require(Health, Team::Inhabitant)]
pub struct Inhabitant;

View file

@ -0,0 +1,17 @@
[package]
name = "inhabitant_coranth"
version = "0.1.0"
edition = "2024"
[dependencies]
bevy = { workspace = true }
avian3d = { workspace = true }
state = { path = "../state" }
combat = { path = "../combat" }
building = { path = "../building" }
inhabitant = { path = "../inhabitant" }
combat_damagers = { path = "../combat_damagers" }
[lints]
workspace = true

View file

@ -0,0 +1,107 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
use bevy::prelude::*;
use building::Building;
use combat::{GaveDamage, Health, Team};
use combat_damagers::ContactDamage;
use inhabitant::Inhabitant;
use state::GameSystemSet;
pub struct InhabitantCoranthPlugin;
impl Plugin for InhabitantCoranthPlugin {
fn build(&self, app: &mut App) {
app.add_event::<SpawnCoranth>()
.add_systems(FixedUpdate, tick.in_set(GameSystemSet::Execute))
.add_systems(FixedUpdate, spawn.in_set(GameSystemSet::PostTick));
}
}
#[derive(Component)]
#[require(Inhabitant)]
pub struct Coranth;
#[derive(Event)]
pub struct SpawnCoranth {
pub transform: Transform,
}
fn spawn(
mut reader: EventReader<SpawnCoranth>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
for SpawnCoranth { transform } in reader.read() {
commands
.spawn((
RigidBody::Dynamic,
Collider::cuboid(0.5, 0.5, 0.5),
Mesh3d(meshes.add(Cuboid::from_length(0.5))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb_u8(220, 156, 86),
metallic: 1.0,
perceptual_roughness: 0.3,
..default()
})),
MaxLinearSpeed(25.),
Coranth,
transform.clone(),
Health::new(5.0),
ContactDamage { amount: 5.0 },
Name::from("Coranth"),
))
.observe(explode);
}
}
fn explode(
trigger: Trigger<GaveDamage>,
spatial_query: SpatialQuery,
trigger_query: Query<&GlobalTransform>,
mut other_query: Query<(&GlobalTransform, &mut LinearVelocity)>,
) {
info!("blasthing!");
let Ok(gtf) = trigger_query.get(trigger.target()) else {
return;
};
let origin = gtf.translation();
for e in spatial_query.shape_intersections(
&Collider::sphere(5.0),
origin,
Quat::IDENTITY,
// &SpatialQueryFilter::from_mask(Team::Inhabitant),
&SpatialQueryFilter::default(),
) {
info!("found hit");
if let Ok((gtf, mut v)) = other_query.get_mut(e) {
let delta = gtf.translation() - origin;
v.0 += delta.normalize_or_zero() * 10.0;
}
}
}
fn tick(
mut coranths: Query<(&GlobalTransform, &mut LinearVelocity), With<Coranth>>,
buildings: Query<&GlobalTransform, With<Building>>,
) {
for (coranth_tf, mut coranth_v) in coranths.iter_mut() {
let coranth_pos = coranth_tf.translation();
if let Some(closest_building) =
buildings
.iter()
.map(|gtf| gtf.translation())
.min_by(|a, b| {
coranth_pos
.distance_squared(*a)
.total_cmp(&coranth_pos.distance_squared(*b))
})
{
let delta = closest_building - coranth_pos;
coranth_v.0 += delta.normalize_or_zero() * 0.1;
}
}
}

View file

@ -12,6 +12,7 @@ camera = { path = "../camera" }
combat = { path = "../combat" } combat = { path = "../combat" }
building_core = { path = "../building_core" } building_core = { path = "../building_core" }
building_impaler = { path = "../building_impaler" } building_impaler = { path = "../building_impaler" }
inhabitant_coranth = { path = "../inhabitant_coranth" }
[lints] [lints]
workspace = true workspace = true

View file

@ -10,9 +10,9 @@ use bevy::{
render::camera::Exposure, render::camera::Exposure,
}; };
use building_core::SpawnCore; use building_core::SpawnCore;
use building_impaler::{Impaler, SpawnImpaler}; use building_impaler::SpawnImpaler;
use camera::ControlledCamera; use camera::ControlledCamera;
use combat::{Defense, Health}; use inhabitant_coranth::SpawnCoranth;
use state::AppState; use state::AppState;
pub struct LevelPlugin; pub struct LevelPlugin;
@ -29,6 +29,7 @@ fn setup(
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
mut core_writer: EventWriter<SpawnCore>, mut core_writer: EventWriter<SpawnCore>,
mut impaler_writer: EventWriter<SpawnImpaler>, mut impaler_writer: EventWriter<SpawnImpaler>,
mut coranth_writer: EventWriter<SpawnCoranth>,
) { ) {
let level_size = 50.0; let level_size = 50.0;
// Static physics object with a collision shape // Static physics object with a collision shape
@ -44,35 +45,10 @@ fn setup(
})), })),
)); ));
// Dynamic physics object with a collision shape and initial angular velocity
for y in 5..15 { for y in 5..15 {
commands coranth_writer.write(SpawnCoranth {
.spawn(( transform: Transform::from_xyz(y as f32 * 0.25, y as f32 * 1.1, 0.0),
RigidBody::Dynamic, });
Collider::cuboid(0.5, 0.5, 0.5),
AngularVelocity(Vec3::new(2.5, 3.5, 1.5)),
Mesh3d(meshes.add(Cuboid::from_length(0.5))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::srgb_u8(220, 156, 86),
metallic: 1.0,
perceptual_roughness: 0.3,
..default()
})),
Transform::from_xyz(0.0, y as f32 * 1.1, 0.0),
Health::new(5.0),
Defense::new(y as f32 - 5.0),
))
.observe(
|trigger: Trigger<Pointer<Click>>,
target: Single<&GlobalTransform, With<Impaler>>,
mut query: Query<(&GlobalTransform, &mut LinearVelocity)>| {
if let Ok((gtf, mut v)) = query.get_mut(trigger.target()) {
let delta = target.translation() - gtf.translation();
v.y += 5.0;
v.0 += delta;
}
},
);
} }
core_writer.write(SpawnCore { core_writer.write(SpawnCore {

View file

@ -9,6 +9,9 @@ pub struct PhysicsPlugin;
impl Plugin for PhysicsPlugin { impl Plugin for PhysicsPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins((PhysicsPlugins::default(), PhysicsPickingPlugin)); app.add_plugins((
PhysicsPlugins::default().set(PhysicsInterpolationPlugin::interpolate_all()),
PhysicsPickingPlugin,
));
} }
} }

View file

@ -13,6 +13,7 @@ fn main() {
state::StatePlugin, state::StatePlugin,
physics::PhysicsPlugin, physics::PhysicsPlugin,
// ui must come before the sub crates // ui must come before the sub crates
(
ui::UiPlugin, ui::UiPlugin,
ui_state::UiStatePlugin, ui_state::UiStatePlugin,
ui_debug::UiDebugPlugin, ui_debug::UiDebugPlugin,
@ -26,6 +27,9 @@ fn main() {
building::BuildingPlugin, building::BuildingPlugin,
building_impaler::BuildingImpalerPlugin, building_impaler::BuildingImpalerPlugin,
combat_damagers::CombatDamagersPlugin, combat_damagers::CombatDamagersPlugin,
),
inhabitant::InhabitantPlugin,
inhabitant_coranth::InhabitantCoranthPlugin,
// new internal crates go here // new internal crates go here
)); ));