biiig cleanup

This commit is contained in:
WanderingPenwing 2024-10-07 17:57:44 +02:00
parent ab804fb9b5
commit 447dfc9f22
5 changed files with 221 additions and 231 deletions

View file

@ -1,14 +1,14 @@
use bevy::prelude::*; use bevy::prelude::*;
use crate::Player;
use crate::GameState; use crate::GameState;
use crate::GameOver; use crate::GameOver;
use crate::GameData;
pub fn setup( pub fn setup(
mut commands: Commands, mut commands: Commands,
_asset_server: Res<AssetServer>, _asset_server: Res<AssetServer>,
mut player_query: Query<&mut Player> game_data: Res<GameData>,
) { ) {
if let Ok(player) = player_query.get_single_mut() {
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), width: Val::Percent(100.0),
@ -43,7 +43,7 @@ pub fn setup(
); );
let bottom_text_node = TextBundle::from_section( let bottom_text_node = TextBundle::from_section(
format!("final score : {}", player.score), format!("final score : {}", game_data.score),
bottom_text_style, bottom_text_style,
); );
@ -52,7 +52,6 @@ pub fn setup(
commands.entity(container).push_children(&[top_text, bottom_text]); commands.entity(container).push_children(&[top_text, bottom_text]);
} }
}
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,

View file

@ -6,14 +6,12 @@ pub fn player_mouse_move (
buttons: Res<ButtonInput<MouseButton>>, buttons: Res<ButtonInput<MouseButton>>,
mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>, mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>,
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>, window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
// debug_line_query: Query<&mut Transform, (With<DebugLine>, Without<Player>)>,
) { ) {
let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else { let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else {
return; return;
}; };
let local_transform = &global_transform.compute_transform(); let local_transform = &global_transform.compute_transform();
// Check if left mouse button is pressed
if !buttons.pressed(MouseButton::Left) { if !buttons.pressed(MouseButton::Left) {
player.dragging_pos = None; player.dragging_pos = None;
return; return;
@ -30,12 +28,10 @@ pub fn player_mouse_move (
return; return;
}; };
// Check if cursor has moved significantly
if old_cursor.distance(new_cursor) < 3.0 { if old_cursor.distance(new_cursor) < 3.0 {
return; return;
} }
// Raycasting from the camera based on the cursor positions
let Some(old_ray) = camera.viewport_to_world(&global_transform, old_cursor) else { let Some(old_ray) = camera.viewport_to_world(&global_transform, old_cursor) else {
return; return;
}; };
@ -44,40 +40,31 @@ pub fn player_mouse_move (
return; return;
}; };
let delta_rotation = rotate_to_align(new_ray, old_ray); // oposite direction and never stop let delta_rotation = rotate_to_align(new_ray, old_ray);
//debug_vector(debug_line_query, new_ray.get_point(SKY_RADIUS), axis*10.0);
player.target_rotation = Some(delta_rotation * local_transform.rotation ); player.target_rotation = Some(delta_rotation * local_transform.rotation );
player.dragging_pos = Some(new_cursor); player.dragging_pos = Some(new_cursor);
} }
fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat { fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
// Step 1: Get the direction vectors from the rays
let pos_1 = ray_1.get_point(1.0); let pos_1 = ray_1.get_point(1.0);
let pos_2 = ray_2.get_point(1.0); let pos_2 = ray_2.get_point(1.0);
// Compute direction vectors let dir_1 = pos_1.normalize();
let dir_1 = (pos_1 - Vec3::ZERO).normalize(); // Change Vec3::ZERO to the origin or a relevant point let dir_2 = pos_2.normalize();
let dir_2 = (pos_2 - Vec3::ZERO).normalize();
// Step 2: Compute the axis of rotation (cross product)
let axis_of_rotation = dir_1.cross(dir_2).normalize(); let axis_of_rotation = dir_1.cross(dir_2).normalize();
// Check if vectors are parallel
if axis_of_rotation.length_squared() < f32::EPSILON { if axis_of_rotation.length_squared() < f32::EPSILON {
return Quat::IDENTITY; return Quat::IDENTITY;
} }
// Step 3: Compute the angle of rotation (dot product and arccosine) let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0);
let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0); // Clamp the value to prevent NaN from acos let angle_of_rotation = dot_product.acos() * 6.0;
let angle_of_rotation = dot_product.acos() * 6.0; // Ensure the angle is in radians
// Handle any potential invalid angle values
if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() { if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() {
return Quat::IDENTITY; return Quat::IDENTITY;
} }
// Step 4: Create a quaternion representing the rotation
Quat::from_axis_angle(axis_of_rotation, angle_of_rotation) Quat::from_axis_angle(axis_of_rotation, angle_of_rotation)
} }

View file

@ -10,6 +10,7 @@ use crate::Sky;
use crate::Constellation; use crate::Constellation;
use crate::ConstellationLine; use crate::ConstellationLine;
use crate::PlayerState; use crate::PlayerState;
use crate::GameData;
use crate::celestial_to_cartesian; use crate::celestial_to_cartesian;
use crate::spawn_cons_lines; use crate::spawn_cons_lines;
@ -167,6 +168,7 @@ pub fn setup(
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>,
mut game_data: ResMut<GameData>,
sky: Res<Sky>, sky: Res<Sky>,
text_query: Query<&mut Text, With<AnswerButton>>, text_query: Query<&mut Text, With<AnswerButton>>,
button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
@ -176,10 +178,12 @@ pub fn player_interact(
meshes: ResMut<Assets<Mesh>>, meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, materials: ResMut<Assets<StandardMaterial>>,
) { ) {
if let Ok((mut player, mut transform)) = player_query.get_single_mut() { let Ok((mut player, mut transform)) = player_query.get_single_mut() else {
return
};
if keys.just_pressed(KeyCode::Space) || player.target_cons_name.is_none() { if keys.just_pressed(KeyCode::Space) || game_data.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state); choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state, game_data);
return return
} }
@ -193,9 +197,9 @@ pub fn player_interact(
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); rotation *= Quat::from_rotation_y((-PI / 60.0) as f32);
} }
if keys.pressed(KeyCode::KeyI) && player.state == PlayerState::Playing { if keys.pressed(KeyCode::KeyI) && game_data.state == PlayerState::Playing {
if let Some(target_cons) = player.target_cons_name.clone() { if let Some(target_cons) = game_data.target_cons_name.clone() {
player.state = PlayerState::Hinted; game_data.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons); spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return return
} }
@ -207,7 +211,7 @@ pub fn player_interact(
} }
if keys.pressed(KeyCode::KeyR) { if keys.pressed(KeyCode::KeyR) {
if let Some(target_constellation_name) = player.target_cons_name.clone() { if let Some(target_constellation_name) = game_data.target_cons_name.clone() {
let mut target_constellation = sky.content[0].clone(); let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() { for constellation in sky.content.clone() {
if constellation.name == target_constellation_name { if constellation.name == target_constellation_name {
@ -241,7 +245,6 @@ pub fn player_interact(
} }
} }
} }
}
pub fn ui_labels( pub fn ui_labels(
mut param_set: ParamSet<( mut param_set: ParamSet<(
@ -249,26 +252,24 @@ pub fn ui_labels(
Query<&mut Text, With<ScoreLabel>>, Query<&mut Text, With<ScoreLabel>>,
Query<&mut Text, With<HintLabel>>, Query<&mut Text, With<HintLabel>>,
)>, )>,
mut player_query: Query<(&mut Player, &mut Transform)>, game_data: Res<GameData>
) { ) {
if let Ok((player, _)) = player_query.get_single_mut() {
if let Ok(mut health_text) = param_set.p0().get_single_mut() { if let Ok(mut health_text) = param_set.p0().get_single_mut() {
health_text.sections[0].value = "# ".repeat(player.health); health_text.sections[0].value = "# ".repeat(game_data.health);
} }
if let Ok(mut score_text) = param_set.p1().get_single_mut() { if let Ok(mut score_text) = param_set.p1().get_single_mut() {
score_text.sections[0].value = format!("{}", player.score); score_text.sections[0].value = format!("{}", game_data.score);
} }
if let Ok(mut hint_text) = param_set.p2().get_single_mut() { if let Ok(mut hint_text) = param_set.p2().get_single_mut() {
if player.state == PlayerState::Answered { if game_data.state == PlayerState::Answered {
hint_text.sections[0].value = "press space to continue".into(); hint_text.sections[0].value = "press space to continue".into();
} else { } else {
hint_text.sections[0].value = "press i to get an hint".into(); hint_text.sections[0].value = "press i to get an hint".into();
} }
} }
} }
}
pub fn ui_buttons( pub fn ui_buttons(
@ -282,15 +283,14 @@ pub fn ui_buttons(
With<Button>, With<Button>,
>, >,
mut text_query: Query<&mut Text, With<AnswerButton>>, mut text_query: Query<&mut Text, With<AnswerButton>>,
mut player_query: Query<&mut Player>, mut game_data: ResMut<GameData>,
commands: Commands, commands: Commands,
meshes: ResMut<Assets<Mesh>>, meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, materials: ResMut<Assets<StandardMaterial>>,
sky: Res<Sky> sky: Res<Sky>
) { ) {
if let Ok(mut player) = player_query.get_single_mut() { if game_data.state == PlayerState::Answered {
if player.state == PlayerState::Answered { return;
return
} }
let mut pressed_button: Option<String> = None; let mut pressed_button: Option<String> = None;
@ -308,23 +308,29 @@ pub fn ui_buttons(
} }
} }
if let Some(selected_cons) = pressed_button { let Some(selected_cons) = pressed_button else {
if let Some(target_cons) = player.target_cons_name.clone() { return;
if player.state == PlayerState::Playing { };
let Some(target_cons) = game_data.target_cons_name.clone() else {
return;
};
if game_data.state == PlayerState::Playing {
spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone()); spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone());
} }
if target_cons == selected_cons { if target_cons == selected_cons {
if player.state == PlayerState::Hinted { if game_data.state == PlayerState::Hinted {
player.score += 20; game_data.score += 20;
} else { } else {
player.score += 100; game_data.score += 100;
} }
} else { } else {
player.health -= 1; game_data.health -= 1;
} }
player.state = PlayerState::Answered; game_data.state = PlayerState::Answered;
for ( for (
_interaction, _interaction,
@ -349,9 +355,6 @@ pub fn ui_buttons(
} }
} }
} }
}
}
}
fn choose_constellation( fn choose_constellation(
player: &mut Player, player: &mut Player,
@ -360,9 +363,10 @@ fn choose_constellation(
mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
constellation_line_query : Query<(Entity, &ConstellationLine)>, constellation_line_query : Query<(Entity, &ConstellationLine)>,
mut commands: Commands, mut commands: Commands,
mut game_state: ResMut<NextState<GameState>> mut game_state: ResMut<NextState<GameState>>,
mut game_data: ResMut<GameData>,
) { ) {
if player.health == 0 { if game_data.health == 0 {
game_state.set(GameState::End); game_state.set(GameState::End);
} }
if sky.content.len() >= 4 { if sky.content.len() >= 4 {
@ -375,7 +379,7 @@ fn choose_constellation(
let target_constellation = &constellations[target_index]; let target_constellation = &constellations[target_index];
player.target_rotation = Some(constellation_center(target_constellation.clone())); player.target_rotation = Some(constellation_center(target_constellation.clone()));
player.target_cons_name = Some(target_constellation.name.clone()); game_data.target_cons_name = Some(target_constellation.name.clone());
info!("Target constellation: {}", target_constellation.name); info!("Target constellation: {}", target_constellation.name);
@ -392,7 +396,7 @@ fn choose_constellation(
commands.entity(entity).despawn(); commands.entity(entity).despawn();
} }
player.state = PlayerState::Playing; game_data.state = PlayerState::Playing;
} else { } else {
info!("Not enough constellations in the sky (need 4)"); info!("Not enough constellations in the sky (need 4)");
} }

View file

@ -46,6 +46,27 @@ struct Sky {
content: Vec<Constellation>, content: Vec<Constellation>,
} }
#[derive(Resource)]
struct GameData {
seen: Vec<Constellation>,
score: usize,
health: usize,
state: PlayerState,
target_cons_name: Option<String>,
}
impl Default for GameData {
fn default() -> Self {
GameData {
seen: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
struct Constellation { struct Constellation {
#[serde(rename = "Name")] #[serde(rename = "Name")]
@ -84,31 +105,15 @@ struct MainGame;
#[derive(Component)] #[derive(Component)]
struct GameOver; struct GameOver;
#[derive(Component)] #[derive(Component, Default)]
struct Player { struct Player {
target_rotation: Option<Quat>, target_rotation: Option<Quat>,
target_cons_name: Option<String>,
score: usize,
health: usize,
state: PlayerState,
dragging_pos: Option<Vec2>, dragging_pos: Option<Vec2>,
} }
impl Default for Player { #[derive(Default, PartialEq)]
fn default() -> Self {
Player {
target_rotation: None,
target_cons_name: None,
score: 0,
health: 3,
state: PlayerState::Playing,
dragging_pos: None,
}
}
}
#[derive(PartialEq)]
enum PlayerState { enum PlayerState {
#[default]
Playing, Playing,
Hinted, Hinted,
Answered, Answered,
@ -126,6 +131,7 @@ fn main() {
App::new() App::new()
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins)
.insert_resource(Sky::default()) .insert_resource(Sky::default())
.insert_resource(GameData::default())
.init_state::<GameState>() .init_state::<GameState>()
.add_systems(Startup, star_setup) .add_systems(Startup, star_setup)
.add_systems(Startup, cons_setup) .add_systems(Startup, cons_setup)
@ -225,6 +231,14 @@ fn star_setup(
Star, Star,
)); ));
} }
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
},
Player::default(),
));
} }
fn get_stars() -> std::io::Result<Vec<StarData>> { fn get_stars() -> std::io::Result<Vec<StarData>> {

View file

@ -1,10 +1,10 @@
use bevy::prelude::*; use bevy::prelude::*;
use std::f64::consts::PI; use std::f64::consts::PI;
//use bevy::input::mouse::MouseMotion; //use bevy::input::mouse::MouseMotion;
use crate::Player;
use crate::GameState; use crate::GameState;
use crate::GameOver;
use crate::StartMenu; use crate::StartMenu;
use crate::GameData;
use crate::Player;
#[derive(Component)] #[derive(Component)]
struct AudioPlayer; struct AudioPlayer;
@ -17,7 +17,10 @@ pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
info!("audio started"); info!("audio started");
} }
pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) { pub fn setup(
mut commands: Commands,
mut game_data: ResMut<GameData>
) {
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), width: Val::Percent(100.0),
@ -61,24 +64,13 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
commands.entity(container).push_children(&[top_text, bottom_text]); commands.entity(container).push_children(&[top_text, bottom_text]);
commands.spawn(( *game_data = GameData::default();
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
},
Player::default(),
GameOver,
));
} }
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut game_state: ResMut<NextState<GameState>>, mut game_state: ResMut<NextState<GameState>>,
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>,
//commands: Commands,
//mut evr_motion: EventReader<MouseMotion>,
//asset_server: Res<AssetServer>,
//mut audio_query: Query<&mut AudioPlayer>,
) { ) {
if keys.just_pressed(KeyCode::Space) { if keys.just_pressed(KeyCode::Space) {
info!("start space"); info!("start space");
@ -86,12 +78,6 @@ pub fn player_interact(
} }
if let Ok((_player, mut transform)) = player_query.get_single_mut() { if let Ok((_player, mut transform)) = player_query.get_single_mut() {
// for _ev in evr_motion.read() {
// if let Err(_) = audio_query.get_single_mut() {
// audio_setup(asset_server, commands);
// }
// }
let mut rotation = Quat::IDENTITY; let mut rotation = Quat::IDENTITY;
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32); rotation *= Quat::from_rotation_y((PI / 6000.0) as f32);
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32); rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32);