diff --git a/src/character.rs b/src/character.rs index 51eed58..36b3c77 100644 --- a/src/character.rs +++ b/src/character.rs @@ -1,4 +1,4 @@ -use crate::game_state::GameState; +use crate::{game_state::GameState, selectable::Selectable}; use crate::mechanics::*; use bevy::prelude::*; use big_brain::prelude::*; @@ -85,6 +85,7 @@ pub fn spawner_system( transform, ..default() }, + Selectable {}, CharacterController { speed: 5.0, color: DEFAULT_COLOR, diff --git a/src/main.rs b/src/main.rs index cdf6d2d..242a760 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,6 @@ use crate::character::SpawnCharacter; +use crate::raycast::PlaneRaycast; +use crate::selectable::{CurrentlySelected, Selectable}; use bevy::input::mouse::*; use bevy::{ diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, @@ -11,6 +13,7 @@ mod game_state; mod main_menu; mod mechanics; mod raycast; +mod selectable; mod splash_screen; #[derive(Component)] @@ -22,7 +25,7 @@ struct PlayerCamera { pub struct PlayerInputPlugin; impl Plugin for PlayerInputPlugin { fn build(&self, app: &mut App) { - app.add_systems(Update, update_player_camera); + app.add_systems(Update, (update_player_camera, object_select)); } } @@ -52,6 +55,7 @@ fn main() { crate::raycast::RaycastPlugin, )); + app.init_resource::(); app.add_systems(Startup, setup); app.run(); @@ -101,6 +105,29 @@ fn setup( )); } +fn object_select( + mut query: Query<&PlaneRaycast, With>, + selectables: Query<(&GlobalTransform, &Selectable, Entity)>, + mbtn: Res>, + mut sel: ResMut, +) { + if !mbtn.just_pressed(MouseButton::Left) { + return; + } + + let raycast = query.single_mut(); + let Some(pos) = raycast.result else { return }; + + let control_distance = 2.0; + + for p in selectables.iter() { + if (p.0.translation() - pos).length() < control_distance { + sel.sel = p.2; + println!("Selected entity with id = {}", p.2.index()); + } + } +} + fn update_player_camera( mut query: Query<(&mut Transform, &PlayerCamera)>, keyboard: Res>, diff --git a/src/selectable.rs b/src/selectable.rs new file mode 100644 index 0000000..4224a7f --- /dev/null +++ b/src/selectable.rs @@ -0,0 +1,17 @@ +use bevy::prelude::*; + +#[derive(Component)] +pub struct Selectable {} + +#[derive(Resource)] +pub struct CurrentlySelected { + pub sel: Entity, +} + +impl Default for CurrentlySelected { + fn default() -> Self { + CurrentlySelected { + sel: Entity::from_raw(u32::MAX), + } + } +}