range indicators, limit tower placement to within range of core

This commit is contained in:
Jim 2025-09-01 19:10:16 -04:00
parent 9c4787f5e2
commit 6a4978041c
Signed by: jim
GPG key ID: 3D7D94BA53088BF4
16 changed files with 350 additions and 60 deletions

13
Cargo.lock generated
View file

@ -1656,6 +1656,7 @@ dependencies = [
"building", "building",
"combat", "combat",
"state", "state",
"ui_range_indicator",
] ]
[[package]] [[package]]
@ -1677,8 +1678,10 @@ dependencies = [
"avian3d", "avian3d",
"bevy", "bevy",
"building", "building",
"combat",
"input", "input",
"physics", "physics",
"ui_range_indicator",
] ]
[[package]] [[package]]
@ -2016,6 +2019,7 @@ dependencies = [
"ui_health_bar", "ui_health_bar",
"ui_ingame", "ui_ingame",
"ui_pause", "ui_pause",
"ui_range_indicator",
"ui_state", "ui_state",
"upgrade", "upgrade",
] ]
@ -5325,6 +5329,15 @@ dependencies = [
"ui_state", "ui_state",
] ]
[[package]]
name = "ui_range_indicator"
version = "0.1.0"
dependencies = [
"bevy",
"combat",
"input",
]
[[package]] [[package]]
name = "ui_state" name = "ui_state"
version = "0.1.0" version = "0.1.0"

View file

@ -57,4 +57,5 @@ building_barrager = { path = "crates/building_barrager" }
resource_graveyard = { path = "crates/resource_graveyard" } resource_graveyard = { path = "crates/resource_graveyard" }
upgrade = { path = "crates/upgrade" } upgrade = { path = "crates/upgrade" }
ui_health_bar = { path = "crates/ui_health_bar" } ui_health_bar = { path = "crates/ui_health_bar" }
ui_range_indicator = { path = "crates/ui_range_indicator" }
#new internal crates go here #new internal crates go here

View file

@ -1,22 +1,22 @@
( (
map: { map: {
KeyCode(ShiftLeft): [
MultiPlaceTower,
],
MouseButton(Middle): [ MouseButton(Middle): [
CameraOrbitEnable, CameraOrbitEnable,
], ],
KeyCode(F1): [
ToggleDebugUI,
],
MouseButton(Right): [ MouseButton(Right): [
PlaceTower, PlaceTower,
], ],
MouseButton(Left): [
CameraPanEnable,
],
KeyCode(ShiftLeft): [
MultiPlaceTower,
],
MouseScroll: [ MouseScroll: [
CameraZoom, CameraZoom,
], ],
KeyCode(F1): [ MouseButton(Left): [
ToggleDebugUI, CameraPanEnable,
], ],
MouseMovementX: [ MouseMovementX: [
CameraYaw, CameraYaw,

View file

@ -8,7 +8,7 @@ use bevy::{
platform::collections::HashMap, platform::collections::HashMap,
prelude::*, prelude::*,
}; };
use combat::{Health, Team}; use combat::{Health, Range, Team};
use input::Selectable; use input::Selectable;
use resources::{Cost, Resources}; use resources::{Cost, Resources};
use state::GameSystemSet; use state::GameSystemSet;
@ -32,6 +32,10 @@ pub struct Building {
pub info: Entity, pub info: Entity,
} }
#[derive(Component)]
#[require(Range)]
pub struct Core;
#[derive(Component, Clone)] #[derive(Component, Clone)]
#[require(Name, Cost, UpgradeTree)] #[require(Name, Cost, UpgradeTree)]
#[component(on_add = register_building_info)] #[component(on_add = register_building_info)]
@ -114,7 +118,13 @@ pub fn valid_placement(
collider_query: &Query<&Building>, collider_query: &Query<&Building>,
size: Vec3, size: Vec3,
position: Vec3, position: Vec3,
core_position_range: Option<(Vec3, f32)>,
) -> bool { ) -> bool {
if let Some((core_position, core_range)) = core_position_range
&& position.distance_squared(core_position) > core_range * core_range
{
return false;
}
!spatial_query !spatial_query
.shape_intersections( .shape_intersections(
// shrink the collider a bit to allow for buildings right next to each other // shrink the collider a bit to allow for buildings right next to each other
@ -133,6 +143,7 @@ fn place_building(
mut resources: ResMut<Resources>, mut resources: ResMut<Resources>,
info_query: Query<(&BuildingInfo, &Cost, &Name), With<UpgradeTree>>, info_query: Query<(&BuildingInfo, &Cost, &Name), With<UpgradeTree>>,
building_query: Query<&Building>, building_query: Query<&Building>,
core_query: Query<(&GlobalTransform, &Range), With<Core>>,
spatial_query: SpatialQuery, spatial_query: SpatialQuery,
) { ) {
for PlaceBuilding { for PlaceBuilding {
@ -150,7 +161,16 @@ fn place_building(
} }
let size_v3 = info.size.as_vec3(); let size_v3 = info.size.as_vec3();
let (collider, position) = info.get_placed_collider_and_position(location.as_vec3()); let (collider, position) = info.get_placed_collider_and_position(location.as_vec3());
if !valid_placement(&spatial_query, &building_query, size_v3, position) { if !valid_placement(
&spatial_query,
&building_query,
size_v3,
position,
core_query
.single()
.ok()
.map(|(gtf, r)| (gtf.translation(), r.0)),
) {
error!("tried to place building colliding with other building"); error!("tried to place building colliding with other building");
continue; continue;
} }

View file

@ -8,7 +8,7 @@ use avian3d::prelude::{Collider, LinearVelocity, RigidBody};
use bevy::prelude::*; use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding}; use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{ use combat::{
Defense, Health, Defense, Health, Range,
projectiles::{Fire, Projectile, ProjectileLauncher, get_shotgun_launch_vectors}, projectiles::{Fire, Projectile, ProjectileLauncher, get_shotgun_launch_vectors},
}; };
use combat_damagers::ContactDamage; use combat_damagers::ContactDamage;
@ -181,9 +181,9 @@ fn populate(
Health::new(20.0), Health::new(20.0),
Defense::new(7.0), Defense::new(7.0),
ContactDamage::new(2.0), ContactDamage::new(2.0),
Range(10.0),
ProjectileLauncher::new( ProjectileLauncher::new(
Duration::from_secs(1), Duration::from_secs(1),
50.0,
5.0, 5.0,
Vec3::Y * (SIZE.y as f32 + 0.5), Vec3::Y * (SIZE.y as f32 + 0.5),
Duration::from_secs(10), Duration::from_secs(10),

View file

@ -9,6 +9,7 @@ bevy = { workspace = true }
combat = { path = "../combat" } combat = { path = "../combat" }
building = { path = "../building" } building = { path = "../building" }
state = { path = "../state" } state = { path = "../state" }
ui_range_indicator = { path = "../ui_range_indicator" }
[lints] [lints]
workspace = true workspace = true

View file

@ -3,8 +3,9 @@
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
use bevy::prelude::*; use bevy::prelude::*;
use building::{BuildingInfo, BuildingPreview, PREVIEW_ALPHA, PopulatePlacedBuilding}; use building::{BuildingInfo, BuildingPreview, Core, PREVIEW_ALPHA, PopulatePlacedBuilding};
use combat::{Defense, Health}; use combat::{Defense, Health, Range};
use ui_range_indicator::{CustomRangeIndicator, DisplayCustomRangeIndicator};
pub struct BuildingCorePlugin; pub struct BuildingCorePlugin;
@ -14,9 +15,6 @@ impl Plugin for BuildingCorePlugin {
} }
} }
#[derive(Component)]
pub struct Core;
#[derive(Resource)] #[derive(Resource)]
struct CoreResources { struct CoreResources {
mesh: Handle<Mesh>, mesh: Handle<Mesh>,
@ -72,6 +70,7 @@ fn register(
fn populate( fn populate(
trigger: Trigger<PopulatePlacedBuilding>, trigger: Trigger<PopulatePlacedBuilding>,
mut commands: Commands, mut commands: Commands,
mut materials: ResMut<Assets<StandardMaterial>>,
res: Res<CoreResources>, res: Res<CoreResources>,
) { ) {
if trigger.event().info != res.info_entity { if trigger.event().info != res.info_entity {
@ -81,7 +80,15 @@ fn populate(
Core, Core,
Health::new(100.0), Health::new(100.0),
Defense::new(5.0), Defense::new(5.0),
Range(20.0),
Mesh3d(res.mesh.clone()), Mesh3d(res.mesh.clone()),
MeshMaterial3d(res.material.clone()), MeshMaterial3d(res.material.clone()),
CustomRangeIndicator::new(materials.add(StandardMaterial {
alpha_mode: AlphaMode::Blend,
base_color: Color::srgba(0.6, 0.2, 0.2, 0.4),
unlit: true,
double_sided: true,
..default()
})),
)); ));
} }

View file

@ -10,6 +10,8 @@ avian3d = { workspace = true }
building = { path = "../building" } building = { path = "../building" }
physics = { path = "../physics" } physics = { path = "../physics" }
input = { path = "../input" } input = { path = "../input" }
combat = { path = "../combat" }
ui_range_indicator = { path = "../ui_range_indicator" }
[lints] [lints]
workspace = true workspace = true

View file

@ -4,9 +4,11 @@
use avian3d::prelude::SpatialQuery; use avian3d::prelude::SpatialQuery;
use bevy::prelude::*; use bevy::prelude::*;
use building::{Building, BuildingInfo, BuildingPreview, PlaceBuilding, valid_placement}; use building::{Building, BuildingInfo, BuildingPreview, Core, PlaceBuilding, valid_placement};
use combat::Range;
use input::{Cancellable, Inputs, Selected, actions::InputAction}; use input::{Cancellable, Inputs, Selected, actions::InputAction};
use physics::Ground; use physics::Ground;
use ui_range_indicator::DisplayCustomRangeIndicator;
pub struct BuildingPlacementPlugin; pub struct BuildingPlacementPlugin;
@ -46,11 +48,59 @@ fn cancel_preview(
} }
} }
fn select_preview(
mut reader: EventReader<SelectBuildingPreview>,
mut old_query: Query<(Entity, &mut Visibility), With<ActiveBuildingPreview>>,
core_query: Query<Entity, With<Core>>,
new_query: Query<(), With<BuildingPreview>>,
mut commands: Commands,
) {
let Some(SelectBuildingPreview(opt_entity)) = reader.read().last() else {
return;
};
for (entity, mut vis) in old_query.iter_mut() {
if *opt_entity != Some(entity) {
commands
.entity(entity)
.remove::<(ActiveBuildingPreview, Cancellable)>();
*vis = Visibility::Hidden;
}
}
let Some(new_entity) = opt_entity else {
if let Ok(core_entity) = core_query.single() {
commands
.entity(core_entity)
.remove::<DisplayCustomRangeIndicator>();
}
return;
};
if !new_query.contains(*new_entity) {
error!("tried to select a building without a preview!");
if let Ok(core_entity) = core_query.single() {
commands
.entity(core_entity)
.remove::<DisplayCustomRangeIndicator>();
}
return;
}
commands.entity(*new_entity).insert((
Visibility::Visible,
ActiveBuildingPreview::default(),
Cancellable,
));
if let Ok(core_entity) = core_query.single() {
commands
.entity(core_entity)
.insert(DisplayCustomRangeIndicator);
}
}
fn move_preview( fn move_preview(
trigger: Trigger<Pointer<Move>>, trigger: Trigger<Pointer<Move>>,
preview: Single<(&mut Transform, &mut ActiveBuildingPreview, &BuildingPreview)>, preview: Single<(&mut Transform, &mut ActiveBuildingPreview, &BuildingPreview)>,
info_query: Query<&BuildingInfo>, info_query: Query<&BuildingInfo>,
building_query: Query<&Building>, building_query: Query<&Building>,
core_query: Query<(&GlobalTransform, &Range), With<Core>>,
spatial_query: SpatialQuery, spatial_query: SpatialQuery,
) { ) {
let Some(dest) = trigger.event().hit.position else { let Some(dest) = trigger.event().hit.position else {
@ -69,6 +119,10 @@ fn move_preview(
&building_query, &building_query,
info.size.as_vec3(), info.size.as_vec3(),
position, position,
core_query
.single()
.ok()
.map(|(gtf, r)| (gtf.translation(), r.0)),
) { ) {
info!("invalid placement!!!!!"); info!("invalid placement!!!!!");
return; return;
@ -96,34 +150,3 @@ fn place_preview(
location: active.0, location: active.0,
}); });
} }
fn select_preview(
mut reader: EventReader<SelectBuildingPreview>,
mut old_query: Query<(Entity, &mut Visibility), With<ActiveBuildingPreview>>,
new_query: Query<(), With<BuildingPreview>>,
mut commands: Commands,
) {
let Some(SelectBuildingPreview(opt_entity)) = reader.read().last() else {
return;
};
for (entity, mut vis) in old_query.iter_mut() {
if *opt_entity != Some(entity) {
commands
.entity(entity)
.remove::<(ActiveBuildingPreview, Cancellable)>();
*vis = Visibility::Hidden;
}
}
let Some(new_entity) = opt_entity else {
return;
};
if !new_query.contains(*new_entity) {
error!("tried to select a building without a preview!");
return;
}
commands.entity(*new_entity).insert((
Visibility::Visible,
ActiveBuildingPreview::default(),
Cancellable,
));
}

View file

@ -253,3 +253,12 @@ fn tick_invulnerability(
} }
} }
} }
#[derive(Component, Deref, DerefMut)]
pub struct Range(pub f32);
impl Default for Range {
fn default() -> Self {
Self(5.)
}
}

View file

@ -10,7 +10,7 @@ use physics::PhysicsLayers;
use rand::{Rng, thread_rng}; use rand::{Rng, thread_rng};
use state::GameSystemSet; use state::GameSystemSet;
use crate::Team; use crate::{Range, Team};
pub(crate) struct ProjectilePlugin; pub(crate) struct ProjectilePlugin;
@ -46,20 +46,18 @@ impl From<&ProjectileLauncher> for Projectile {
} }
#[derive(Component, Clone)] #[derive(Component, Clone)]
#[require(Team)] #[require(Team, Range)]
pub struct ProjectileLauncher { pub struct ProjectileLauncher {
pub fire_timer: Timer, pub fire_timer: Timer,
pub fire_offset: Vec3, pub fire_offset: Vec3,
pub spread: f32, pub spread: f32,
pub lifetime: Duration, pub lifetime: Duration,
pub range: f32,
pub damage: f32, pub damage: f32,
} }
impl ProjectileLauncher { impl ProjectileLauncher {
pub fn new( pub fn new(
fire_interval: Duration, fire_interval: Duration,
range: f32,
damage: f32, damage: f32,
fire_offset: Vec3, fire_offset: Vec3,
lifetime: Duration, lifetime: Duration,
@ -67,7 +65,6 @@ impl ProjectileLauncher {
) -> Self { ) -> Self {
Self { Self {
fire_timer: Timer::new(fire_interval, TimerMode::Once), fire_timer: Timer::new(fire_interval, TimerMode::Once),
range,
spread, spread,
damage, damage,
fire_offset, fire_offset,
@ -91,13 +88,19 @@ pub struct Fire {
fn fire_launcher( fn fire_launcher(
mut commands: Commands, mut commands: Commands,
mut launcher_query: Query<(Entity, &mut ProjectileLauncher, &Team, &GlobalTransform)>, mut launcher_query: Query<(
Entity,
&mut ProjectileLauncher,
&Range,
&Team,
&GlobalTransform,
)>,
spatial_query: SpatialQuery, spatial_query: SpatialQuery,
enemy_query: Query<(&Team, &GlobalTransform)>, enemy_query: Query<(&Team, &GlobalTransform)>,
time: Res<Time>, time: Res<Time>,
) { ) {
let delta = time.delta(); let delta = time.delta();
for (launcher_entity, mut launcher, team, gtf) in launcher_query.iter_mut() { for (launcher_entity, mut launcher, range, team, gtf) in launcher_query.iter_mut() {
// see if enough time has passed to shoot // see if enough time has passed to shoot
launcher.fire_timer.tick(delta); launcher.fire_timer.tick(delta);
if !launcher.fire_timer.finished() { if !launcher.fire_timer.finished() {
@ -106,7 +109,7 @@ fn fire_launcher(
// see if enemy in range // see if enemy in range
let enemies = spatial_query.shape_intersections( let enemies = spatial_query.shape_intersections(
&Collider::sphere(launcher.range), &Collider::sphere(range.0),
gtf.translation(), gtf.translation(),
Quat::default(), Quat::default(),
&SpatialQueryFilter::from_mask(team.enemy_layers()), &SpatialQueryFilter::from_mask(team.enemy_layers()),

View file

@ -91,7 +91,7 @@ pub enum BasePhaseState {
impl Default for BasePhaseState { impl Default for BasePhaseState {
fn default() -> Self { fn default() -> Self {
Self::Plan { phase: 0 } Self::Plan { phase: 1 }
} }
} }

View file

@ -155,14 +155,14 @@ fn transition_ui(
return; return;
} }
egui::Window::new("TRANSITION") egui::Window::new("TRANSITION")
.resizable(false)
.collapsible(false) .collapsible(false)
.title_bar(false) .title_bar(false)
.anchor(Align2::CENTER_CENTER, [0., 0.]) .anchor(Align2::CENTER_CENTER, [0., 0.])
.fixed_size([600., 200.])
.show(ctx, |ui| { .show(ctx, |ui| {
ui.label( ui.label(
RichText::new(format!( RichText::new(format!(
"{} {}", "{} PHASE {}",
match curr_transition.get() { match curr_transition.get() {
PhaseTransitionState::None => "WHAT", PhaseTransitionState::None => "WHAT",
PhaseTransitionState::ToExecute => "EXECUTE", PhaseTransitionState::ToExecute => "EXECUTE",

View file

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

View file

@ -0,0 +1,197 @@
//bevy system signatures often violate these rules
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]
use std::f32::consts::PI;
use bevy::{
ecs::{component::HookContext, world::DeferredWorld},
pbr::{NotShadowCaster, NotShadowReceiver},
prelude::*,
};
use combat::Range;
use input::Selected;
pub struct UiRangeIndicatorPlugin;
impl Plugin for UiRangeIndicatorPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, init).add_systems(Update, display);
}
}
#[derive(Component)]
struct Indicator(Entity, f32);
#[derive(Component)]
struct SelectedIndicator;
#[derive(Component, Default)]
#[component(on_add=create_custom_indicator)]
#[component(on_remove=remove_custom_indicator)]
pub struct CustomRangeIndicator {
material: Handle<StandardMaterial>,
indicator: Option<Entity>,
}
#[derive(Component)]
pub struct DisplayCustomRangeIndicator;
#[derive(Resource)]
struct RangeResources {
base_mesh: Handle<Mesh>,
}
impl CustomRangeIndicator {
pub fn new(material: Handle<StandardMaterial>) -> Self {
Self {
material,
indicator: None,
}
}
}
fn create_custom_indicator(mut world: DeferredWorld, ctx: HookContext) {
let attaching_to = ctx.entity;
let material = world
.entity(attaching_to)
.get::<CustomRangeIndicator>()
.unwrap()
.material
.clone();
let base_mesh = world.resource::<RangeResources>().base_mesh.clone();
let mut commands = world.commands();
let indicator = create_indicator(&mut commands, material, base_mesh);
world
.entity_mut(attaching_to)
.get_mut::<CustomRangeIndicator>()
.unwrap()
.indicator = Some(indicator);
}
fn remove_custom_indicator(mut world: DeferredWorld, ctx: HookContext) {
let Some(indicator) = world
.entity(ctx.entity)
.get::<CustomRangeIndicator>()
.unwrap()
.indicator
else {
return;
};
world.commands().entity(indicator).despawn();
}
fn create_indicator(
commands: &mut Commands,
material: Handle<StandardMaterial>,
base_mesh: Handle<Mesh>,
) -> Entity {
commands
.spawn((
Mesh3d(base_mesh),
Transform::from_rotation(Quat::from_rotation_x(-PI / 2.)),
MeshMaterial3d(material),
Indicator(Entity::PLACEHOLDER, 1.0),
Visibility::Hidden,
NotShadowCaster,
NotShadowReceiver,
))
.id()
}
fn init(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
let material = materials.add(StandardMaterial {
alpha_mode: AlphaMode::Blend,
base_color: Color::srgba(0.7, 0.7, 0.7, 0.5),
unlit: true,
double_sided: true,
..default()
});
let mesh = meshes.add(Extrusion::new(Annulus::new(1000. - 0.1, 1000.), 1.0));
commands.insert_resource(RangeResources {
base_mesh: mesh.clone(),
});
let selected_indicator = create_indicator(&mut commands, material, mesh);
commands
.entity(selected_indicator)
.insert(SelectedIndicator);
}
// todo - perf and visuals kind of suck here. honeslty this whole thing should be split up and sucks.
fn display(
selected_query: Query<
(Entity, &Range, &GlobalTransform),
(With<Selected>, Without<CustomRangeIndicator>),
>,
selected_indicator_query: Single<
(&mut Transform, &mut Visibility, &mut Indicator, &mut Mesh3d),
With<SelectedIndicator>,
>,
custom_entity_query: Query<(
Entity,
&Range,
&GlobalTransform,
&CustomRangeIndicator,
Option<&Selected>,
Option<&DisplayCustomRangeIndicator>,
)>,
mut indicator_query: Query<
(&mut Transform, &mut Visibility, &mut Indicator, &mut Mesh3d),
Without<SelectedIndicator>,
>,
mut meshes: ResMut<Assets<Mesh>>,
) {
for (
target_entity,
range,
gtf,
CustomRangeIndicator { indicator, .. },
opt_selected,
opt_display,
) in custom_entity_query.iter()
{
let Some(indicator_entity) = indicator else {
continue;
};
let Ok((mut tf, mut vis, mut indicator, mut mesh)) =
indicator_query.get_mut(*indicator_entity)
else {
error!("invalid setup for custom range indicator");
continue;
};
if target_entity != indicator.0 || indicator.1 != range.0 {
indicator.0 = target_entity; //shouldn't ever be different after init, but just to be sure...
indicator.1 = range.0;
// range or entity changed, generate new mesh
mesh.0 = meshes.add(Extrusion::new(Annulus::new(range.0 - 0.1, range.0), 1.0));
}
*vis = if opt_selected.is_some() || opt_display.is_some() {
Visibility::Inherited
} else {
Visibility::Hidden
};
tf.translation = gtf.translation().with_y(1.0);
}
//update selected entity
{
let (mut tf, mut vis, mut indicator, mut mesh) = selected_indicator_query.into_inner();
let Ok((entity, range, gtf)) = selected_query.single() else {
*vis = Visibility::Hidden;
return;
};
if entity != indicator.0 || indicator.1 != range.0 {
indicator.0 = entity;
indicator.1 = range.0;
// range or entity changed, generate new mesh
mesh.0 = meshes.add(Extrusion::new(Annulus::new(range.0 - 0.1, range.0), 1.0));
}
*vis = Visibility::Inherited;
tf.translation = gtf.translation().with_y(1.0);
}
}

View file

@ -38,6 +38,7 @@ fn main() {
resource_graveyard::ResourceGraveyardPlugin, resource_graveyard::ResourceGraveyardPlugin,
upgrade::UpgradePlugin, upgrade::UpgradePlugin,
ui_health_bar::UiHealthBarPlugin, ui_health_bar::UiHealthBarPlugin,
ui_range_indicator::UiRangeIndicatorPlugin,
// new internal crates go here // new internal crates go here
)); ));