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,57 +1,56 @@
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), height: Val::Percent(100.0),
height: Val::Percent(100.0), flex_direction: FlexDirection::Column,
flex_direction: FlexDirection::Column, justify_content: JustifyContent::Center,
justify_content: JustifyContent::Center, align_items: AlignItems::Center,
align_items: AlignItems::Center, ..default()
..default() },
}, ..default()
..default() };
};
let container = commands.spawn(container_node).id(); let container = commands.spawn(container_node).id();
let top_text_style = TextStyle { let top_text_style = TextStyle {
font_size: 50.0, font_size: 50.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default() ..default()
}; };
let bottom_text_style = TextStyle { let bottom_text_style = TextStyle {
font_size: 30.0, font_size: 30.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // font: asset_server.load("fonts/FiraSans-Regular.ttf"),
..default() ..default()
}; };
let top_text_node = TextBundle::from_section( let top_text_node = TextBundle::from_section(
"Game Over", "Game Over",
top_text_style, top_text_style,
); );
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,
); );
let top_text = commands.spawn((top_text_node, GameOver)).id(); let top_text = commands.spawn((top_text_node, GameOver)).id();
let bottom_text = commands.spawn((bottom_text_node, GameOver)).id(); let bottom_text = commands.spawn((bottom_text_node, GameOver)).id();
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(

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,71 +178,72 @@ 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) || game_data.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state, game_data);
return
}
let mut rotation = Quat::IDENTITY;
if keys.just_pressed(KeyCode::Space) || player.target_cons_name.is_none() { if keys.pressed(KeyCode::KeyA) {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state); rotation *= Quat::from_rotation_y((PI / 60.0) as f32);
}
if keys.pressed(KeyCode::KeyD) {
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32);
}
if keys.pressed(KeyCode::KeyI) && game_data.state == PlayerState::Playing {
if let Some(target_cons) = game_data.target_cons_name.clone() {
game_data.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return return
} }
}
let mut rotation = Quat::IDENTITY; if rotation != Quat::IDENTITY {
transform.rotation *= rotation;
if keys.pressed(KeyCode::KeyA) { player.target_rotation = None;
rotation *= Quat::from_rotation_y((PI / 60.0) as f32); }
}
if keys.pressed(KeyCode::KeyD) { if keys.pressed(KeyCode::KeyR) {
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); if let Some(target_constellation_name) = game_data.target_cons_name.clone() {
}
if keys.pressed(KeyCode::KeyI) && player.state == PlayerState::Playing {
if let Some(target_cons) = player.target_cons_name.clone() {
player.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return
}
}
if rotation != Quat::IDENTITY {
transform.rotation *= rotation;
player.target_rotation = None;
}
if keys.pressed(KeyCode::KeyR) {
if let Some(target_constellation_name) = player.target_cons_name.clone() {
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
player.target_rotation = Some(constellation_center(target_constellation));
}
}
if keys.pressed(KeyCode::KeyW) {
let target_constellation_name: String = "Ursa Minor".into();
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 {
target_constellation = constellation target_constellation = constellation
} }
} }
player.target_rotation = Some(constellation_center(target_constellation)); player.target_rotation = Some(constellation_center(target_constellation));
}
}
if keys.pressed(KeyCode::KeyW) {
let target_constellation_name: String = "Ursa Minor".into();
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
player.target_rotation = Some(constellation_center(target_constellation));
}
if let Some(target_rotation) = player.target_rotation {
let current_rotation = transform.rotation;
transform.rotation = current_rotation.slerp(target_rotation, 0.1);
if transform.rotation.angle_between(target_rotation) < 0.01 {
player.target_rotation = None;
} }
}
if let Some(target_rotation) = player.target_rotation {
let current_rotation = transform.rotation;
transform.rotation = current_rotation.slerp(target_rotation, 0.1);
if transform.rotation.angle_between(target_rotation) < 0.01 {
player.target_rotation = None;
}
}
}
} }
pub fn ui_labels( pub fn ui_labels(
@ -249,24 +252,22 @@ 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(game_data.health);
health_text.sections[0].value = "# ".repeat(player.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();
} }
}
} }
} }
@ -282,75 +283,77 @@ 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;
for (
for ( interaction,
interaction, _color,
_color, _border_color,
_border_color, children
children ) in &mut interaction_query {
) in &mut interaction_query { if *interaction == Interaction::Pressed {
if *interaction == Interaction::Pressed { if let Ok(text) = text_query.get_mut(children[0]) {
if let Ok(text) = text_query.get_mut(children[0]) { pressed_button = Some(text.sections[0].value.clone());
pressed_button = Some(text.sections[0].value.clone());
}
} }
} }
if let Some(selected_cons) = pressed_button {
if let Some(target_cons) = player.target_cons_name.clone() {
if player.state == PlayerState::Playing {
spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone());
}
if target_cons == selected_cons {
if player.state == PlayerState::Hinted {
player.score += 20;
} else {
player.score += 100;
}
} else {
player.health -= 1;
}
player.state = PlayerState::Answered;
for (
_interaction,
mut color,
mut border_color,
children
) in &mut interaction_query {
if let Ok(text) = text_query.get_mut(children[0]) {
let button_text = text.sections[0].value.clone();
*color = if button_text == target_cons {
RIGHT_BUTTON.into()
} else {
WRONG_BUTTON.into()
};
border_color.0 = if button_text == selected_cons {
Color::WHITE
} else {
Color::BLACK
};
}
}
}
}
} }
let Some(selected_cons) = pressed_button else {
return;
};
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());
}
if target_cons == selected_cons {
if game_data.state == PlayerState::Hinted {
game_data.score += 20;
} else {
game_data.score += 100;
}
} else {
game_data.health -= 1;
}
game_data.state = PlayerState::Answered;
for (
_interaction,
mut color,
mut border_color,
children
) in &mut interaction_query {
if let Ok(text) = text_query.get_mut(children[0]) {
let button_text = text.sections[0].value.clone();
*color = if button_text == target_cons {
RIGHT_BUTTON.into()
} else {
WRONG_BUTTON.into()
};
border_color.0 = if button_text == selected_cons {
Color::WHITE
} else {
Color::BLACK
};
}
}
} }
fn choose_constellation( fn choose_constellation(
@ -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);