projectile system

This commit is contained in:
Jim 2025-08-31 19:00:19 -04:00
parent 918b4884b2
commit ad4a2cf393
Signed by: jim
GPG key ID: 3D7D94BA53088BF4
17 changed files with 400 additions and 23 deletions

17
Cargo.lock generated
View file

@ -1632,10 +1632,22 @@ dependencies = [
]
[[package]]
name = "building_core"
name = "building_barrager"
version = "0.1.0"
dependencies = [
"avian3d",
"bevy",
"building",
"combat",
"combat_damagers",
"resources",
"state",
]
[[package]]
name = "building_core"
version = "0.1.0"
dependencies = [
"bevy",
"building",
"combat",
@ -1646,7 +1658,6 @@ dependencies = [
name = "building_impaler"
version = "0.1.0"
dependencies = [
"avian3d",
"bevy",
"building",
"combat",
@ -1979,6 +1990,7 @@ dependencies = [
"bevy",
"bevy-inspector-egui",
"building",
"building_barrager",
"building_core",
"building_impaler",
"building_placement",
@ -3003,6 +3015,7 @@ checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"
name = "inhabitant"
version = "0.1.0"
dependencies = [
"avian3d",
"bevy",
"combat",
"resources",

View file

@ -53,4 +53,5 @@ inhabitant_coranth = { path = "crates/inhabitant_coranth" }
building_placement = { path = "crates/building_placement" }
ui_ingame = { path = "crates/ui_ingame" }
resources = { path = "crates/resources" }
building_barrager = { path = "crates/building_barrager" }
#new internal crates go here

View file

@ -197,14 +197,14 @@ fn place_building(
mut building_map: ResMut<PlacedBuildings>,
mut commands: Commands,
mut resources: ResMut<Resources>,
info_query: Query<(&BuildingInfo, &Cost)>,
info_query: Query<(&BuildingInfo, &Cost, &Name)>,
) {
for PlaceBuilding {
info: info_entity,
location,
} in reader.read()
{
let Ok((info, cost)) = info_query.get(*info_entity) else {
let Ok((info, cost, name)) = info_query.get(*info_entity) else {
error!("tried to place building without info!");
continue;
};
@ -228,6 +228,9 @@ fn place_building(
BuildingPosition(*location),
Collider::cuboid(size_v3.x, size_v3.y, size_v3.z),
Mesh3d::default(),
name.clone(),
RigidBody::Static,
Team::Core.collision_layers(),
))
.id();
building_map.place_building(*location, info, *info_entity, instance);

View file

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

View file

@ -0,0 +1,133 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::{f32, time::Duration};
use avian3d::prelude::{Collider, LinearVelocity, RigidBody};
use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{
Defense, Health,
projectiles::{Fire, Projectile, ProjectileLauncher, get_launch_vector},
};
use combat_damagers::ContactDamage;
use resources::Cost;
pub struct BuildingBarragerPlugin;
impl Plugin for BuildingBarragerPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, register).add_observer(populate);
}
}
#[derive(Component)]
pub struct Barrager;
#[derive(Resource)]
struct BuildingResources {
mesh: Handle<Mesh>,
material: Handle<StandardMaterial>,
projectile_mesh: Handle<Mesh>,
projectile_material: Handle<StandardMaterial>,
projectile_collider: Collider,
info_entity: Entity,
}
const SIZE: UVec3 = UVec3::splat(2);
const PROJ_SIZE: Vec3 = Vec3::splat(0.25);
fn register(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let mesh = meshes.add(Cuboid::from_length(2.0));
let base_material = StandardMaterial {
base_color: Color::srgb_u8(0x3d, 0x95, 0xa5),
metallic: 0.2,
perceptual_roughness: 0.6,
..default()
};
let material = materials.add(base_material.clone());
let preview_material = materials.add(StandardMaterial {
alpha_mode: AlphaMode::Blend,
base_color: base_material.base_color.with_alpha(PREVIEW_ALPHA),
..base_material
});
let info = commands.spawn_empty().id();
let preview = commands
.spawn((
BuildingPreview { info },
Visibility::Hidden,
Mesh3d(mesh.clone()),
MeshMaterial3d(preview_material),
))
.id();
commands.entity(info).insert((
BuildingInfo {
preview,
size: SIZE,
unlocked: true,
},
Cost { souls: 0, bones: 0 },
Name::new("Barrager"),
));
commands.insert_resource(BuildingResources {
mesh: mesh,
material: material.clone(),
projectile_material: material,
projectile_mesh: meshes.add(Cuboid::from_size(PROJ_SIZE)),
projectile_collider: Collider::cuboid(PROJ_SIZE.x, PROJ_SIZE.y, PROJ_SIZE.z),
info_entity: info,
});
}
fn populate(
trigger: Trigger<PopulatePlacedBuilding>,
mut commands: Commands,
res: Res<BuildingResources>,
) {
if trigger.event().info != res.info_entity {
return;
}
commands
.entity(trigger.target())
.insert((
Barrager,
Health::new(20.0),
Defense::new(7.0),
ContactDamage::new(2.0),
ProjectileLauncher::new(
Duration::from_secs(1),
50.0,
5.0,
Vec3::Y * (SIZE.y as f32 + 0.5),
Duration::from_secs(10),
),
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
))
.observe(on_fire);
}
fn on_fire(trigger: Trigger<Fire>, mut commands: Commands, res: Res<BuildingResources>) {
commands.spawn((
RigidBody::Dynamic,
trigger.event().team,
Health::new(1.0),
ContactDamage::projectile(5.0, f32::INFINITY),
Transform::from_translation(trigger.event().spawn_pos),
Projectile::from(&trigger.event().launcher),
LinearVelocity(get_launch_vector(
trigger.event().spawn_pos,
trigger.event().target_pos,
5.0,
)),
res.projectile_collider.clone(),
MeshMaterial3d(res.projectile_material.clone()),
Mesh3d(res.projectile_mesh.clone()),
));
}

View file

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

View file

@ -2,7 +2,6 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health};
@ -79,11 +78,9 @@ fn populate(
return;
}
commands.entity(trigger.target()).insert((
RigidBody::Static,
Core,
Health::new(100.0),
Defense::new(5.0),
Name::from("Core"),
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
));

View file

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

View file

@ -2,7 +2,6 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health};
@ -82,12 +81,10 @@ fn populate(
return;
}
commands.entity(trigger.target()).insert((
RigidBody::Static,
Impaler,
Health::new(20.0),
Defense::new(5.0),
ContactDamage { amount: 5.0 },
Name::from("Impaler"),
ContactDamage::new(5.0),
Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()),
));

View file

@ -2,6 +2,8 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
pub mod projectiles;
use std::time::Duration;
use avian3d::prelude::*;
@ -13,7 +15,8 @@ pub struct CombatPlugin;
impl Plugin for CombatPlugin {
fn build(&self, app: &mut App) {
app.add_observer(on_attack)
app.add_plugins(projectiles::ProjectilePlugin)
.add_observer(on_attack)
.add_observer(on_die)
.add_systems(
FixedUpdate,
@ -23,7 +26,7 @@ impl Plugin for CombatPlugin {
}
}
#[derive(PhysicsLayer, Default, Component, Clone, Debug, PartialEq, Eq, Reflect)]
#[derive(PhysicsLayer, Default, Component, Clone, Copy, Debug, PartialEq, Eq, Reflect)]
pub enum Team {
#[default]
Core,
@ -37,6 +40,12 @@ impl Team {
Team::Inhabitant => CollisionLayers::new(Team::Inhabitant, LayerMask::ALL),
}
}
pub fn enemy_layers(&self) -> LayerMask {
match self {
Team::Core => Team::Inhabitant.into(),
Team::Inhabitant => Team::Core.into(),
}
}
}
#[derive(Event, Debug, Default)]

View file

@ -0,0 +1,148 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::time::Duration;
use avian3d::prelude::*;
use bevy::prelude::*;
use state::GameSystemSet;
use crate::Team;
pub(crate) struct ProjectilePlugin;
impl Plugin for ProjectilePlugin {
fn build(&self, app: &mut App) {
app.add_systems(FixedUpdate, fire_launcher.in_set(GameSystemSet::Execute));
}
}
#[derive(Component)]
#[require(Team)]
pub struct Projectile {
pub lifetime: Duration,
}
impl From<&ProjectileLauncher> for Projectile {
fn from(value: &ProjectileLauncher) -> Self {
Self {
lifetime: value.lifetime,
}
}
}
#[derive(Component, Clone)]
#[require(Team)]
pub struct ProjectileLauncher {
pub fire_timer: Timer,
pub fire_offset: Vec3,
pub lifetime: Duration,
pub range: f32,
pub damage: f32,
}
impl ProjectileLauncher {
pub fn new(
fire_interval: Duration,
range: f32,
damage: f32,
fire_offset: Vec3,
lifetime: Duration,
) -> Self {
Self {
fire_timer: Timer::new(fire_interval, TimerMode::Once),
range,
damage,
fire_offset,
lifetime,
}
}
}
#[derive(Event)]
pub struct Fire {
pub target: Entity,
pub target_pos: Vec3,
pub spawn_pos: Vec3,
pub launcher: ProjectileLauncher,
pub team: Team,
}
fn fire_launcher(
mut commands: Commands,
mut launcher_query: Query<(Entity, &mut ProjectileLauncher, &Team, &GlobalTransform)>,
spatial_query: SpatialQuery,
enemy_query: Query<(&Team, &GlobalTransform)>,
time: Res<Time>,
) {
let delta = time.delta();
for (launcher_entity, mut launcher, team, gtf) in launcher_query.iter_mut() {
// see if enough time has passed to shoot
launcher.fire_timer.tick(delta);
if !launcher.fire_timer.finished() {
continue;
}
// see if enemy in range
let enemies = spatial_query.shape_intersections(
&Collider::sphere(launcher.range),
gtf.translation(),
Quat::default(),
&SpatialQueryFilter::from_mask(team.enemy_layers()),
);
if enemies.is_empty() {
continue;
}
let Some((closest_enemy, enemy_pos)) = enemies
.iter()
.filter_map(|e| {
enemy_query
.get(*e)
.ok()
.and_then(|(enemy_team, enemy_gtf)| {
if enemy_team != team {
Some((*e, enemy_gtf.translation()))
} else {
None
}
})
})
.min_by(|(_, a), (_, b)| {
gtf.translation()
.distance_squared(*a)
.total_cmp(&gtf.translation().distance_squared(*b))
})
else {
info!("no closest enemy, is someone on the wrong physics layer for their team?");
return;
};
launcher.fire_timer.reset();
commands.trigger_targets(
Fire {
target: closest_enemy,
target_pos: enemy_pos,
spawn_pos: gtf.translation() + launcher.fire_offset,
launcher: launcher.clone(),
team: team.clone(),
},
[launcher_entity],
);
}
}
/// may shoot higher than height if delta y is too big
pub fn get_launch_vector(start: Vec3, target: Vec3, height: f32) -> Vec3 {
// actually +/-, but go with + for now
let delta_y = target.y - start.y;
let height = height.max(delta_y);
let v_y = -1. + (1. + 2. * height).sqrt();
let t = (2. * (delta_y - v_y) / (-9.81)).sqrt();
let delta_x_vector = target.with_y(0.) - start.with_y(0.);
let delta_x = delta_x_vector.length();
let v_x = delta_x / t;
return v_x * delta_x_vector / delta_x + Vec3::Y * v_y;
}

View file

@ -18,10 +18,29 @@ impl Plugin for CombatDamagersPlugin {
}
}
#[derive(Component)]
#[derive(Component, Default)]
#[require(CollisionEventsEnabled)]
pub struct ContactDamage {
pub amount: f32,
pub skip_invulnerability: bool,
pub self_damage: f32,
}
impl ContactDamage {
pub fn new(amount: f32) -> Self {
Self {
amount,
..default()
}
}
pub fn projectile(amount: f32, self_damage: f32) -> Self {
Self {
amount,
skip_invulnerability: true,
self_damage,
}
}
}
fn deal_contact_damage(
@ -35,20 +54,40 @@ fn deal_contact_damage(
Attacked {
attacker: Some(event.0),
amount: contact.amount,
..default()
skip_invulnerability: contact.skip_invulnerability,
},
event.1,
);
if contact.self_damage > 0. {
commands.trigger_targets(
Attacked {
attacker: None,
amount: contact.self_damage,
skip_invulnerability: true,
},
event.0,
);
}
}
if let Ok(contact) = query.get(event.1) {
commands.trigger_targets(
Attacked {
attacker: Some(event.1),
amount: contact.amount,
..default()
skip_invulnerability: contact.skip_invulnerability,
},
event.0,
);
if contact.self_damage > 0. {
commands.trigger_targets(
Attacked {
attacker: None,
amount: contact.self_damage,
skip_invulnerability: true,
},
event.1,
);
}
}
}
}

View file

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

View file

@ -2,6 +2,7 @@
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use avian3d::prelude::*;
use bevy::prelude::*;
use combat::{Health, Team};
use resources::Drops;
@ -13,5 +14,5 @@ impl Plugin for InhabitantPlugin {
}
#[derive(Component, Default)]
#[require(Health, Team::Inhabitant, Drops)]
#[require(CollisionLayers=Team::Inhabitant.collision_layers(), Health, Team::Inhabitant, Drops)]
pub struct Inhabitant;

View file

@ -5,7 +5,7 @@
use avian3d::prelude::*;
use bevy::prelude::*;
use building::Building;
use combat::{GaveDamage, Health};
use combat::{GaveDamage, Health, Team};
use combat_damagers::ContactDamage;
use inhabitant::Inhabitant;
use state::GameSystemSet;
@ -51,8 +51,9 @@ fn spawn(
Coranth,
transform.clone(),
Health::new(5.0),
ContactDamage { amount: 5.0 },
ContactDamage::new(5.0),
Name::from("Coranth"),
Team::Inhabitant.collision_layers(),
))
.observe(explode);
}

View file

@ -39,16 +39,34 @@ fn resource_ui(
.anchor(Align2::RIGHT_TOP, [0., 0.])
.show(ctx, |ui| {
ui.label(RichText::new(format!("Souls: {}", resources.souls)).size(large_font_size));
ui.label(RichText::new(format!("Bones: {}", resources.bones)).size(large_font_size));
ui.heading(RichText::new("Buildings").underline());
for (info, cost, name) in buildings.iter() {
if !info.unlocked {
continue;
}
let souls_text = if cost.souls > 0 {
format!("{} souls", cost.souls)
} else {
"".to_string()
};
let divider_text = if cost.souls > 0 && cost.bones > 0 {
", "
} else if cost.souls == 0 && cost.bones == 0 {
"FREE!!!"
} else {
""
};
let bones_text = if cost.bones > 0 {
format!("{} bones", cost.bones)
} else {
"".to_string()
};
if ui
.button(
RichText::new(format!(
"{} - {} souls, {} bones",
name, cost.souls, cost.bones
"{} - {}{}{}",
name, souls_text, divider_text, bones_text
))
.size(font_size),
)

View file

@ -34,6 +34,7 @@ fn main() {
building_placement::BuildingPlacementPlugin,
ui_ingame::UiIngamePlugin,
resources::ResourcesPlugin,
building_barrager::BuildingBarragerPlugin,
// new internal crates go here
));