diff --git a/assets/images/id_card_toolbar.png b/assets/images/id_card_toolbar.png new file mode 100644 index 0000000..c4bb27a Binary files /dev/null and b/assets/images/id_card_toolbar.png differ diff --git a/assets/main.assets.ron b/assets/main.assets.ron index d01bbfe..80405c4 100644 --- a/assets/main.assets.ron +++ b/assets/main.assets.ron @@ -1,10 +1,12 @@ ({ "lebron": File (path: "images/KingLebron.png"), - "flash_hold_4": File (path: "images/pixelart/Flashlight_hold_4.png"), - "flash_hold_4_pressed": File (path: "images/pixelart/Flashlight_click_4.png"), "house": File (path: "meshes/House.glb"), - "flashlight_click": File (path: "audio/flashlight-switch.ogg"), "library": Folder ( path: "meshes/library", ), + "id_card": File(path: "meshes/id_card.glb"), + "id_card_toolbar": File(path: "images/id_card_toolbar.png"), + "flash_hold_4": File (path: "images/pixelart/Flashlight_hold_4.png"), + "flash_hold_4_pressed": File (path: "images/pixelart/Flashlight_click_4.png"), + "flashlight_click": File (path: "audio/flashlight-switch.ogg"), }) diff --git a/assets/meshes/id_card.glb b/assets/meshes/id_card.glb new file mode 100644 index 0000000..61c4824 Binary files /dev/null and b/assets/meshes/id_card.glb differ diff --git a/src/asset_loading/mod.rs b/src/asset_loading/mod.rs index a2ab2e5..ecd367f 100644 --- a/src/asset_loading/mod.rs +++ b/src/asset_loading/mod.rs @@ -9,19 +9,18 @@ use bevy_kira_audio::{AudioPlugin, AudioSource}; /// Loads resources and assets for the game. /// See assets/main.assets.ron for the actual paths used. pub(super) fn plugin(app: &mut App) { - app.add_plugins(AudioPlugin) - .add_loading_state( - LoadingState::new(GameState::Loading) - .continue_to_state(GameState::Menu) - .with_dynamic_assets_file::("main.assets.ron") - .load_collection::() - .load_collection::() - .load_collection::() - .load_collection::(), - // .load_collection::() - // .load_collection::() - // .load_collection::(), - ); + app.add_plugins(AudioPlugin).add_loading_state( + LoadingState::new(GameState::Loading) + .continue_to_state(GameState::Menu) + .with_dynamic_assets_file::("main.assets.ron") + .load_collection::() + .load_collection::() + .load_collection::() + .load_collection::(), + // .load_collection::() + // .load_collection::() + // .load_collection::(), + ); } // the following asset collections will be loaded during the State `GameState::InitialLoading` @@ -37,6 +36,8 @@ pub(crate) struct AudioAssets { pub(crate) struct GltfAssets { #[asset(key = "library", collection(typed, mapped))] pub(crate) library: HashMap>, + #[asset(key = "id_card")] + pub(crate) card: Handle, } #[derive(AssetCollection, Resource, Clone)] @@ -52,6 +53,8 @@ pub(crate) struct ConfigAssets {} pub(crate) struct ImageAssets { #[asset(key = "lebron")] pub(crate) king: Handle, + #[asset(key = "id_card_toolbar")] + pub(crate) id_card: Handle, } #[derive(AssetCollection, Resource, Clone)] diff --git a/src/interaction/mod.rs b/src/interaction/mod.rs index d175524..031e8ba 100644 --- a/src/interaction/mod.rs +++ b/src/interaction/mod.rs @@ -3,6 +3,9 @@ use bevy::prelude::*; mod objects; mod ui; +#[derive(Component)] +pub struct Interact; + pub fn plugin(app: &mut App) { app.add_plugins((ui::plugin, objects::plugin)); } diff --git a/src/interaction/objects.rs b/src/interaction/objects.rs index fefcdd1..705b479 100644 --- a/src/interaction/objects.rs +++ b/src/interaction/objects.rs @@ -1,40 +1,80 @@ -use bevy::{prelude::*}; -use bevy_rapier3d::prelude::{Collider, RigidBody}; +use bevy::prelude::*; +use bevy_rapier3d::prelude::ColliderDisabled; -use crate::{GameState, asset_loading::GltfAssets}; +use crate::{ + player::{Player, PlayerAction, toolbar::Item}, + util::single_mut, +}; -pub fn plugin(app: &mut App) { - app.add_systems(OnEnter(GameState::Playing), spawn); +use super::{Interact, ui::InteractionOpportunity}; + +pub fn plugin(_app: &mut App) {} + +pub fn handle_pick_up( + mut commands: Commands, + // current action + mut action: Query<(&PlayerAction, &mut Item), With>, + mut vis_query: Query<&mut Visibility>, + children: Query<&mut Children>, + + // current interactable + mut interaction_opportunity: ResMut, +) { + let (action, mut item) = single_mut!(action); + if *action == PlayerAction::PickUp { + // take out the interaction, because we are picking it up + let Some(target) = interaction_opportunity.0.take() else { + return; + }; + let replaced = item.set_item(target); + if let Ok(mut vis) = vis_query.get_mut(target) { + *vis = Visibility::Hidden; + } + if let Ok(colliders) = children.get(target) { + for &collider in colliders { + commands.entity(collider).insert(ColliderDisabled); + } + } + if let Some(dropped) = replaced { + if let Ok(mut vis) = vis_query.get_mut(dropped) { + *vis = Visibility::Visible; + } + if let Ok(colliders) = children.get(dropped) { + for &collider in colliders { + commands.entity(collider).remove::(); + } + } + } + } } -#[derive(Component)] -pub struct Interact; - -fn spawn(mut commands: Commands, models: Res>, gltf_assets: Res) { - let hammer = gltf_assets - .library - .get("meshes/library/hammer.glb") - .unwrap(); - - let hammer = models.get(hammer).unwrap(); - let asset = hammer.default_scene.as_ref().unwrap(); - // hammer - commands - .spawn(( - Transform::from_xyz(0.0, 100.0, 0.0).with_scale(Vec3::splat(0.1)), - Interact, - RigidBody::Dynamic, - SceneRoot(asset.clone()), - )) - .with_children(|parent| { - parent - .spawn(Collider::cuboid(0.8, 10f32, 0.8)) - .insert(Transform::from_xyz(0.0, -5.0, 0.0)); - parent - .spawn(Collider::cuboid(1.0, 1.0, 4.5)) - // Position the collider relative to the rigid-body. - .insert(Transform::from_xyz(0.0, 4.2, 1.0)); - }); - - //tools +pub fn handle_drop( + mut commands: Commands, + // current action + mut action: Query<(&PlayerAction, &Transform, &mut Item), With>, + mut vis_query: Query<&mut Visibility>, + mut item_transform: Query<&mut Transform, With>, + children: Query<&mut Children>, +) { + // let (action, transform, mut item) = single_mut!(action); + // if *action == PlayerAction::Drop { + // if let Ok(mut vis) = vis_query.get_mut(target) { + // *vis = Visibility::Hidden; + // } + // if let Ok(colliders) = children.get(target) { + // for &collider in colliders { + // commands.entity(collider).insert(ColliderDisabled); + // } + // } + // if let Some(dropped) = replaced { + // if let Ok(mut vis) = vis_query.get_mut(dropped) { + // *vis = Visibility::Visible; + // } + // if let Ok(colliders) = children.get(dropped) { + // for &collider in colliders { + // commands.entity(collider).remove::(); + // } + // } + // } + // } } diff --git a/src/interaction/ui.rs b/src/interaction/ui.rs index 708bd87..e2ca24f 100644 --- a/src/interaction/ui.rs +++ b/src/interaction/ui.rs @@ -1,78 +1,93 @@ use crate::GameState; +use crate::player::toolbar::Item; use crate::player::{Player, PlayerAction}; use crate::util::{single, single_mut}; use bevy::{prelude::*, window::PrimaryWindow}; use bevy_egui::{EguiContexts, EguiPlugin, egui}; -use std::f32::consts::TAU; +use bevy_rapier3d::prelude::*; +use bevy_rapier3d::rapier::prelude::CollisionEventFlags; +use std::iter; -use super::objects::Interact; +use super::{Interact, objects}; pub(super) fn plugin(app: &mut App) { app.add_plugins(EguiPlugin) .init_resource::() .add_systems( Update, - (update_interaction_opportunities, display_interaction_prompt) + ( + update_interaction_opportunities, + display_interaction_prompt, + (objects::handle_pick_up, objects::handle_drop), + ) .chain() .run_if(in_state(GameState::Playing)), ); } #[derive(Debug, Clone, Eq, PartialEq, Resource, Default)] -struct InteractionOpportunity(Option); +pub struct InteractionOpportunity(pub Option); fn update_interaction_opportunities( - player_query: Query<&GlobalTransform, With>, + mut collision_events: EventReader, + player_query: Query>, parents: Query<&Parent>, - target_query: Query< - (Entity, &GlobalTransform), - (Without, Without, With), - >, + target_query: Query, With)>, mut interaction_opportunity: ResMut, ) { - interaction_opportunity.0 = None; - let player_transform = single!(player_query); + let player = single!(player_query); - let (target_entity, target_transform) = single!(target_query); + for event in collision_events.read() { + let (e1, e2, started) = match event { + CollisionEvent::Started(e1, e2, CollisionEventFlags::SENSOR) => (*e1, *e2, true), + CollisionEvent::Stopped(e1, e2, CollisionEventFlags::SENSOR) => (*e1, *e2, false), + _ => { + continue; + } + }; - let player_translation = player_transform.translation(); - let target_translation = target_transform.translation(); - if player_translation.distance(target_translation) <= 2.0 { - interaction_opportunity.0.replace(target_entity); + let sensor = match player { + p if p == e1 => e2, + p if p == e2 => e1, + _ => continue, + }; + let mut ancestors = iter::once(sensor).chain(parents.iter_ancestors(sensor)); + + let Some(interactable) = ancestors.find_map(|entity| target_query.get(entity).ok()) else { + continue; + }; + + if started { + interaction_opportunity.0.replace(interactable); + } else { + interaction_opportunity.0.take_if(|t| *t == interactable); + } } } -fn is_facing_target( - player: Vec3, - target: Vec3, - camera_transform: Transform, - camera: &Camera, -) -> bool { - let camera_to_player = camera_transform.forward(); - let player_to_target = target - player; - let angle = camera_to_player.angle_between(player_to_target); - angle < TAU / 8. -} - fn display_interaction_prompt( interaction_opportunity: Res, mut egui_contexts: EguiContexts, - action: Query<&PlayerAction, With>, primary_windows: Query<&Window, With>, + names: Query<&Name, With>, // only the interactables ofcourse ) { let Some(opportunity) = interaction_opportunity.0 else { return; }; let window = single!(primary_windows); + let entity_name = names + .get(opportunity) + .map(|name| name.as_str()) + .expect("A named Interactable object"); + + // objective or item egui::Window::new("Interaction") .collapsible(false) .title_bar(false) .auto_sized() .fixed_pos(egui::Pos2::new(window.width() / 2., window.height() / 2.)) .show(egui_contexts.ctx_mut(), |ui| { - ui.label("E: Pick Up"); + ui.label(format!("E: Pick Up {entity_name}")); }); - - let action = single!(action); } diff --git a/src/level_instantiation/mod.rs b/src/level_instantiation/mod.rs index 828a395..dc64127 100644 --- a/src/level_instantiation/mod.rs +++ b/src/level_instantiation/mod.rs @@ -1,15 +1,24 @@ use std::collections::HashMap; use bevy::prelude::*; -use bevy_rapier3d::prelude::{Collider, RigidBody}; +use bevy_rapier3d::prelude::*; use rand::Rng; -use crate::{asset_loading::GltfAssets, GameState}; +use crate::{ + GameState, + asset_loading::{GltfAssets, ImageAssets}, + interaction::Interact, + player::toolbar::ItemIcon, +}; pub fn map_plugin(app: &mut App) { - app.add_systems(OnEnter(GameState::Playing), spawn_level); + app.add_systems( + OnEnter(GameState::Playing), + (spawn_level, spawn_objects).chain(), + ); } + fn spawn_level( mut commands: Commands, mut meshes: ResMut>, @@ -18,39 +27,74 @@ fn spawn_level( gltf_assets: Res ) { println!("LIBRARY: {:?}", gltf_assets.library); - let mesh_names = ["corner_inside", "corner_outside", "wall", "door", "round_door", "round_hole"]; + let mesh_names = [ + "corner_inside", + "corner_outside", + "wall", + "door", + "round_door", + "round_hole", + ]; let shapes = mesh_names.map(|mesh_name| { let collider: Vec<(Collider, Transform)> = match mesh_name { - "corner_inside" => vec![ - (Collider::cuboid(0.2, 1.0, 0.2), Transform::from_xyz(1.0, 1.0, 1.0).with_rotation(Quat::from_rotation_y(45.0_f32.to_radians()))) - ], + "corner_inside" => vec![( + Collider::cuboid(0.2, 1.0, 0.2), + Transform::from_xyz(1.0, 1.0, 1.0) + .with_rotation(Quat::from_rotation_y(45.0_f32.to_radians())), + )], "corner_outside" => vec![ - (Collider::cuboid(1.0, 1.0, 0.1), Transform::from_xyz(0.0, 1.0, -1.0)), - (Collider::cuboid(1.0, 1.0, 0.1), Transform::from_xyz(-1.0, 1.0, 0.0) - .with_rotation(Quat::from_rotation_y(90.0_f32.to_radians()))), - ], - "wall" => vec![ - (Collider::cuboid(1.0, 1.0, 0.1), Transform::from_xyz(0.0, 1.0, -1.0)) - ], - "door" => vec![ - (Collider::cuboid(1.0, 1.0, 0.1), Transform::from_xyz(0.0, 1.0, -1.0)) - ], - "round_door" => vec![ - (Collider::cuboid(1.0, 1.0, 0.1), Transform::from_xyz(0.0, 1.0, -1.0)) + ( + Collider::cuboid(1.0, 1.0, 0.1), + Transform::from_xyz(0.0, 1.0, -1.0), + ), + ( + Collider::cuboid(1.0, 1.0, 0.1), + Transform::from_xyz(-1.0, 1.0, 0.0) + .with_rotation(Quat::from_rotation_y(90.0_f32.to_radians())), + ), ], + "wall" => vec![( + Collider::cuboid(1.0, 1.0, 0.1), + Transform::from_xyz(0.0, 1.0, -1.0), + )], + "door" => vec![( + Collider::cuboid(1.0, 1.0, 0.1), + Transform::from_xyz(0.0, 1.0, -1.0), + )], + "round_door" => vec![( + Collider::cuboid(1.0, 1.0, 0.1), + Transform::from_xyz(0.0, 1.0, -1.0), + )], "round_hole" => vec![ - (Collider::cuboid(0.2, 1.0, 0.2), Transform::from_xyz(1.0, 1.0, -1.0).with_rotation(Quat::from_rotation_y(45.0_f32.to_radians()))), - (Collider::cuboid(0.2, 1.0, 0.2), Transform::from_xyz(-1.0, 1.0, -1.0).with_rotation(Quat::from_rotation_y(45.0_f32.to_radians()))) - ], - _ => vec![ - (Collider::cuboid(1.0, 0.1, 1.0), Transform::from_xyz(0.0, 0.0, 0.0)) + ( + Collider::cuboid(0.2, 1.0, 0.2), + Transform::from_xyz(1.0, 1.0, -1.0) + .with_rotation(Quat::from_rotation_y(45.0_f32.to_radians())), + ), + ( + Collider::cuboid(0.2, 1.0, 0.2), + Transform::from_xyz(-1.0, 1.0, -1.0) + .with_rotation(Quat::from_rotation_y(45.0_f32.to_radians())), + ), ], + _ => vec![( + Collider::cuboid(1.0, 0.1, 1.0), + Transform::from_xyz(0.0, 0.0, 0.0), + )], }; let path = format!("meshes/library/space_{}.glb", mesh_name); - let handle = gltf_assets.library.get(&path).expect(&format!("Couldn't find {} in library", mesh_name)); - let gltf = models.get(handle).expect(&format!("No model for {}", mesh_name)); + let handle = gltf_assets + .library + .get(&path) + .expect(&format!("Couldn't find {} in library", mesh_name)); + let gltf = models + .get(handle) + .expect(&format!("No model for {}", mesh_name)); - let asset = gltf.default_scene.as_ref().expect(&format!("No scene in {}", mesh_name)); + let asset = gltf + .default_scene + .as_ref() + .expect(&format!("No scene in {}", mesh_name)); (SceneRoot(asset.clone()), collider) }); let [ @@ -59,10 +103,9 @@ fn spawn_level( wall, door, round_door, - round_hole + round_hole, ] = shapes.clone(); - // huge floor commands.spawn(( RigidBody::Fixed, @@ -215,6 +258,7 @@ fn spawn_level( } } + fn create_maps(n: i32) -> Vec { let mut maps = Vec::new(); let mut initial_node = MapNode::new(); @@ -298,7 +342,6 @@ impl GameMap { m.generate_map(); m } - fn generate_map(&mut self) { let mut first_point = self.initial_point.clone(); first_point.1 += 1; @@ -316,7 +359,11 @@ impl GameMap { if self.pos_within_boundaries(pos) { Side::Closed } else { - if rand::rng().random_bool(0.5) { Side::Connection } else { Side::Closed } + if rand::rng().random_bool(0.5) { + Side::Connection + } else { + Side::Closed + } } } @@ -419,3 +466,44 @@ impl GameMap { } } } + +fn spawn_objects( + mut commands: Commands, + models: Res>, + gltf_assets: Res, + image_assets: Res, +) { + + // id card + let card = models.get(&gltf_assets.card).unwrap(); + let asset = card.default_scene.as_ref().unwrap(); + + commands + .spawn(( + Transform::from_xyz(0.0, 2.0, 2.0), + Interact, + RigidBody::Dynamic, + Name::new("Id Card 1"), + Visibility::Visible, + ItemIcon::new(image_assets.id_card.clone()), + SceneRoot(asset.clone()), + )) + .with_children(|parent| { + parent.spawn(( + ColliderMassProperties::Mass(10.0), + Collider::cuboid(0.05, 0.05, 0.01), + Transform::from_rotation(Quat::from_euler( + EulerRot::XYZ, + -10.0f32.to_radians(), // X-axis rotation (tilt) + -5.0f32.to_radians(), // Y-axis rotation + 10.0f32.to_radians(), // Z-axis rotation + )), + )); + parent.spawn(( + ActiveEvents::COLLISION_EVENTS, + Transform::default(), + Collider::ball(0.5), // Interaction radius + Sensor, + )); + }); +} diff --git a/src/main.rs b/src/main.rs index 4554a3a..1641f01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,12 +4,12 @@ use bevy_rapier3d::prelude::*; mod asset_loading; mod bevy_plugin; +mod debugging; mod interaction; mod level_instantiation; mod main_menu; mod player; mod util; -mod debugging; fn main() { App::new() @@ -49,7 +49,7 @@ fn setup( mut commands: Commands, mut meshes: ResMut>, mut materials: ResMut>, - image: Res + image: Res, ) { // circular base commands.spawn(( diff --git a/src/player.rs b/src/player.rs index 97e84be..059be77 100644 --- a/src/player.rs +++ b/src/player.rs @@ -1,4 +1,3 @@ - use bevy::{ input::mouse::AccumulatedMouseMotion, pbr::VolumetricFog, prelude::*, render::view::RenderLayers, window::{PrimaryWindow, WindowResized} }; @@ -7,7 +6,10 @@ use bevy_rapier3d::prelude::*; pub mod toolbar; -use crate::{asset_loading::{AudioAssets, FlashlightAssets}, GameState}; +use crate::{ + GameState, + asset_loading::{AudioAssets, FlashlightAssets}, +}; #[derive(Debug, Component, Default)] pub struct Player { @@ -70,7 +72,6 @@ impl Default for FlashlightButtonAnimation { } } - pub fn plugin(app: &mut App) { app.add_plugins(toolbar::plugin) .add_systems(OnEnter(GameState::Playing), (init_player, hide_cursor)) @@ -83,7 +84,8 @@ pub fn plugin(app: &mut App) { on_resize_system, handle_flashlight, update_flashlight_button_animation, - ).run_if(in_state(GameState::Playing)), + ) + .run_if(in_state(GameState::Playing)), ) .add_systems( FixedUpdate, @@ -196,9 +198,11 @@ fn flashlight_base_transform(window_width: f32, window_height: f32) -> BaseTrans let xoffset = window_size.x / 4.0 - 40.0; let yoffset = 15.0; - let mut transform = Transform::from_translation( - Vec3::new(window_size.x / 2.0 - world_size.x / 2.0 - xoffset, -window_size.y / 2.0 + world_size.y / 2.0 - yoffset, 0.0) - ); + let mut transform = Transform::from_translation(Vec3::new( + window_size.x / 2.0 - world_size.x / 2.0 - xoffset, + -window_size.y / 2.0 + world_size.y / 2.0 - yoffset, + 0.0, + )); transform.scale = Vec3::new(scale, scale, 1.0); return BaseTransform(transform); } @@ -237,8 +241,10 @@ pub(crate) enum PlayerAction { Move, Sprint, Jump, - Interact, - ToggleFlashlight + ToggleFlashlight, + // Objects and stuff + PickUp, + Drop, } pub fn handle_input( @@ -276,7 +282,10 @@ pub fn handle_input( player.speed_factor = 1.0; } if keyboard_input.just_pressed(KeyCode::KeyE) { - *action = PlayerAction::Interact + *action = PlayerAction::PickUp; + } + if keyboard_input.just_pressed(KeyCode::KeyQ) { + *action = PlayerAction::Drop; } if keyboard_input.just_pressed(KeyCode::KeyF) { *action = PlayerAction::ToggleFlashlight; @@ -286,7 +295,9 @@ pub fn handle_input( } } -pub fn apply_player_movement(mut player_query: Query<(&PlayerInput, &mut Velocity, &Player), With>) { +pub fn apply_player_movement( + mut player_query: Query<(&PlayerInput, &mut Velocity, &Player), With>, +) { const SPEED: f32 = 2.6; const JUMP_FORCE: f32 = 4.0; @@ -311,14 +322,18 @@ pub fn apply_head_bob( time: Res