Compare commits

..

No commits in common. "a00a66ab1eb7308dc0c23a07edd07f79c9f75073" and "f27f783501ec0f4820f8e3e92af20f9c7e8dfbce" have entirely different histories.

9 changed files with 312 additions and 432 deletions

1
.gitignore vendored
View file

@ -1,2 +1 @@
/target
/out

34
Cargo.lock generated
View file

@ -216,7 +216,6 @@ dependencies = [
"rand",
"serde",
"serde_json",
"wasm-bindgen",
]
[[package]]
@ -2197,9 +2196,9 @@ dependencies = [
[[package]]
name = "js-sys"
version = "0.3.69"
version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d"
checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
dependencies = [
"wasm-bindgen",
]
@ -3624,19 +3623,20 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.92"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8"
checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
dependencies = [
"cfg-if",
"once_cell",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.92"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da"
checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
dependencies = [
"bumpalo",
"log",
@ -3649,9 +3649,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.42"
version = "0.4.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0"
checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed"
dependencies = [
"cfg-if",
"js-sys",
@ -3661,9 +3661,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.92"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726"
checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@ -3671,9 +3671,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.92"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7"
checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
dependencies = [
"proc-macro2",
"quote",
@ -3684,15 +3684,15 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.92"
version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96"
checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
[[package]]
name = "web-sys"
version = "0.3.69"
version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef"
checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0"
dependencies = [
"js-sys",
"wasm-bindgen",

View file

@ -8,7 +8,6 @@ bevy = { version = "0.14.2", features = [ "dynamic_linking" ] }
rand = "0.8.5"
serde = {version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
wasm-bindgen = "=0.2.92"
# Enable a small amount of optimization in the dev profile.
[profile.dev]
@ -17,6 +16,3 @@ opt-level = 1
# Enable a large amount of optimization in the dev profile for dependencies.
[profile.dev.package."*"]
opt-level = 3
[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"

View file

@ -2,6 +2,3 @@
A Stellarium game made for The icam Game jam 2024, using the Bevy game engine
Star data from : [YaleBrightStarCatalog (Bretton Wade)](https://github.com/brettonw/YaleBrightStarCatalog/blob/master/bsc5-short.json) (MIT License, Copyright (c) 2016 Bretton Wade)
Constellation data from :[Lizard Tail (Isana Kashiwai)](https://www.lizard-tail.com/isana/lab/starlitnight/)

View file

@ -1,56 +1,63 @@
use bevy::prelude::*;
use crate::Player;
use crate::GameState;
use crate::GameOver;
use crate::GameData;
pub fn setup(
mut commands: Commands,
_asset_server: Res<AssetServer>,
game_data: Res<GameData>,
mut player_query: Query<&mut Player>
) {
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
};
if let Ok(player) = player_query.get_single_mut() {
// Create a container node that places its children (text areas) in a vertical column and centers them
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, // Center horizontally
..default()
},
..default()
};
let container = commands.spawn(container_node).id();
let container = commands.spawn(container_node).id();
let top_text_style = TextStyle {
font_size: 50.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
// TextStyle for the top text (larger font)
let top_text_style = TextStyle {
font_size: 50.0, // Larger font size
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
..default()
};
let bottom_text_style = TextStyle {
font_size: 30.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"),
..default()
};
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle {
font_size: 30.0, // Smaller font size
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default()
};
let top_text_node = TextBundle::from_section(
"Game Over",
top_text_style,
);
// TextBundle for the top text
let top_text_node = TextBundle::from_section(
"Game Over", // Text for the top section
top_text_style,
);
let bottom_text_node = TextBundle::from_section(
format!("final score : {}", game_data.score),
bottom_text_style,
);
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section(
format!("final score : {}", player.score), // Text for the bottom section
bottom_text_style,
);
let top_text = commands.spawn((top_text_node, GameOver)).id();
let bottom_text = commands.spawn((bottom_text_node, GameOver)).id();
// Spawn the text nodes and add them as children to the container
let top_text = commands.spawn((top_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(

View file

@ -1,70 +0,0 @@
use bevy::prelude::*;
use crate::Player;
pub fn player_mouse_move (
buttons: Res<ButtonInput<MouseButton>>,
mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>,
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
) {
let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else {
return;
};
let local_transform = &global_transform.compute_transform();
if !buttons.pressed(MouseButton::Left) {
player.dragging_pos = None;
return;
}
let window = window_query.single();
let Some(new_cursor) = window.cursor_position() else {
return;
};
let Some(old_cursor) = player.dragging_pos else {
player.dragging_pos = Some(new_cursor);
return;
};
if old_cursor.distance(new_cursor) < 3.0 {
return;
}
let Some(old_ray) = camera.viewport_to_world(&global_transform, old_cursor) else {
return;
};
let Some(new_ray) = camera.viewport_to_world(&global_transform, new_cursor) else {
return;
};
let delta_rotation = rotate_to_align(new_ray, old_ray);
player.target_rotation = Some(delta_rotation * local_transform.rotation );
player.dragging_pos = Some(new_cursor);
}
fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
let pos_1 = ray_1.get_point(1.0);
let pos_2 = ray_2.get_point(1.0);
let dir_1 = pos_1.normalize();
let dir_2 = pos_2.normalize();
let axis_of_rotation = dir_1.cross(dir_2).normalize();
if axis_of_rotation.length_squared() < f32::EPSILON {
return Quat::IDENTITY;
}
let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0);
let angle_of_rotation = dot_product.acos() * 6.0;
if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() {
return Quat::IDENTITY;
}
Quat::from_axis_angle(axis_of_rotation, angle_of_rotation)
}

View file

@ -7,10 +7,8 @@ use crate::Player;
use crate::GameState;
use crate::MainGame;
use crate::Sky;
use crate::Constellation;
use crate::ConstellationLine;
use crate::PlayerState;
use crate::GameData;
use crate::celestial_to_cartesian;
use crate::spawn_cons_lines;
@ -31,36 +29,36 @@ pub struct ScoreLabel;
#[derive(Component)]
pub struct HintLabel;
pub fn setup(
mut commands: Commands,
mut game_data: ResMut<GameData>,
sky: Res<Sky>,
) {
pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
// Create a container node that places its children (buttons) at the bottom of the screen
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center,
align_items: AlignItems::FlexEnd,
padding: UiRect::all(Val::Px(10.0)),
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Row, // Arrange children in a row (horizontal)
justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::FlexEnd, // Place at the bottom of the screen
padding: UiRect::all(Val::Px(10.0)), // Optional padding
..default()
},
..default()
};
// Button style (same for all buttons)
let button_style = Style {
width: Val::Px(150.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(10.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
margin: UiRect::all(Val::Px(10.0)), // Add margin between buttons
justify_content: JustifyContent::Center, // Center text horizontally
align_items: AlignItems::Center, // Center text vertically
border: UiRect::all(Val::Px(5.0)),
..default()
};
// Create the container for the buttons
let container = commands.spawn(container_node).id();
// Function to create buttons with different text
for _i in 1..=4 {
let button_node = ButtonBundle {
style: button_style.clone(),
@ -79,6 +77,7 @@ pub fn setup(
},
);
// Spawn the button and its text as children of the container
let button = commands.spawn((button_node, MainGame)).id();
let button_text = commands.spawn((button_text_node, AnswerButton, MainGame)).id();
@ -86,11 +85,12 @@ pub fn setup(
commands.entity(container).push_children(&[button]);
}
// Label style for top corners
let label_style = Style {
position_type: PositionType::Absolute,
width: Val::Auto,
height: Val::Auto,
margin: UiRect::all(Val::Px(10.0)),
position_type: PositionType::Absolute, // Absolute positioning
width: Val::Auto, // Auto width to fit text
height: Val::Auto, // Auto height to fit text
margin: UiRect::all(Val::Px(10.0)), // Margin around the text
..default()
};
@ -103,7 +103,7 @@ pub fn setup(
..label_style.clone()
},
text: Text::from_section(
"* * *",
"* * *", // Text content
TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0,
@ -123,7 +123,7 @@ pub fn setup(
..label_style.clone()
},
text: Text::from_section(
"0",
"0", // Text content
TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0,
@ -134,13 +134,14 @@ pub fn setup(
..default()
};
// Centered container for the "Hint" label
let centered_container_node = NodeBundle {
style: Style {
position_type: PositionType::Absolute,
width: Val::Percent(100.0),
top: Val::Px(20.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
width: Val::Percent(100.0), // Full width
top: Val::Px(20.0), // Positioned at the top
justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::Center, // Center vertically
..default()
},
..default()
@ -157,122 +158,103 @@ pub fn setup(
},
);
// Spawn the top left and top right labels
commands.spawn((top_left_label_node, MainGame, HealthLabel));
commands.spawn((top_right_label_node, MainGame, ScoreLabel));
// Create a parent container and then spawn the hint label inside it
let centered_container = commands.spawn(centered_container_node).id();
let hint_label = commands.spawn((hint_label_node, MainGame, HintLabel)).id();
commands.entity(centered_container).push_children(&[hint_label]);
*game_data = GameData::default();
game_data.content = sky.as_string();
}
pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>,
mut game_data: ResMut<GameData>,
sky: Res<Sky>,
mut player_query: Query<(&mut Player, &mut Transform)>, // Query to get Player and Transform
sky: Res<Sky>, // Res to access the Sky resource
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>>, // Query to reset button colors
constellation_line_query : Query<(Entity, &ConstellationLine)>,
commands: Commands,
game_state: ResMut<NextState<GameState>>,
meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>,
) {
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.pressed(KeyCode::KeyA) {
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);
if let Ok((mut player, mut transform)) = player_query.get_single_mut() {
// If the space key was just pressed
if keys.just_pressed(KeyCode::Space) || player.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state);
return
}
}
}
if rotation != Quat::IDENTITY {
transform.rotation *= rotation;
player.target_rotation = None;
}
let mut rotation = Quat::IDENTITY;
if keys.pressed(KeyCode::KeyR) {
if let Some(target_constellation_name) = game_data.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));
}
}
// Rotate left when the A key is pressed
if keys.pressed(KeyCode::KeyA) {
rotation *= Quat::from_rotation_y((PI / 60.0) as f32); // Rotate by 3 degrees (PI/60 radians)
}
if keys.pressed(KeyCode::KeyW) {
let target_constellation_name: String = "Ursa Minor".into();
// Rotate right when the D key is pressed
if keys.pressed(KeyCode::KeyD) {
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); // Rotate by -3 degrees
}
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
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);
}
}
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 {
// Apply the rotation to the transform
if rotation != Quat::IDENTITY {
transform.rotation *= rotation; // Apply the rotation
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(
mut param_set: ParamSet<(
Query<&mut Text, With<HealthLabel>>,
Query<&mut Text, With<ScoreLabel>>,
Query<&mut Text, With<HintLabel>>,
)>,
game_data: Res<GameData>
mut player_query: Query<(&mut Player, &mut Transform)>,
) {
if let Ok(mut health_text) = param_set.p0().get_single_mut() {
health_text.sections[0].value = "# ".repeat(game_data.health);
}
if let Ok((player, _)) = player_query.get_single_mut() {
// Update the health label
if let Ok(mut health_text) = param_set.p0().get_single_mut() {
health_text.sections[0].value = "# ".repeat(player.health);
}
if let Ok(mut score_text) = param_set.p1().get_single_mut() {
score_text.sections[0].value = format!("{}", game_data.score);
}
// Update the score label
if let Ok(mut score_text) = param_set.p1().get_single_mut() {
score_text.sections[0].value = format!("{}", player.score);
}
if let Ok(mut hint_text) = param_set.p2().get_single_mut() {
if game_data.state == PlayerState::Answered {
hint_text.sections[0].value = "press space to continue".into();
} else {
hint_text.sections[0].value = "press i to get an hint".into();
}
if let Ok(mut hint_text) = param_set.p2().get_single_mut() {
if player.state == PlayerState::Answered {
hint_text.sections[0].value = "press space to continue".into();
} else {
hint_text.sections[0].value = "press i to get an hint".into();
}
}
}
}
@ -288,139 +270,128 @@ pub fn ui_buttons(
With<Button>,
>,
mut text_query: Query<&mut Text, With<AnswerButton>>,
mut game_data: ResMut<GameData>,
mut player_query: Query<&mut Player>,
commands: Commands,
meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>,
sky: Res<Sky>
) {
if game_data.state == PlayerState::Answered {
return;
}
if let Ok(mut player) = player_query.get_single_mut() {
if player.state == PlayerState::Answered {
return
}
let mut pressed_button: Option<String> = None;
let mut pressed_button: Option<String> = None;
for (
interaction,
_color,
_border_color,
children
) in &mut interaction_query {
if *interaction == Interaction::Pressed {
if let Ok(text) = text_query.get_mut(children[0]) {
pressed_button = Some(text.sections[0].value.clone());
for (
interaction,
_color,
_border_color,
children
) in &mut interaction_query {
if *interaction == Interaction::Pressed {
if let Ok(text) = text_query.get_mut(children[0]) {
pressed_button = Some(text.sections[0].value.clone());
}
}
}
}
let Some(selected_cons) = pressed_button else {
return;
};
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());
}
let Some(target_cons) = game_data.target_cons_name.clone() else {
return;
};
if target_cons == selected_cons {
if player.state == PlayerState::Hinted {
player.score += 20;
} else {
player.score += 100;
}
} else {
player.health -= 1;
}
if game_data.state == PlayerState::Playing {
spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone());
}
player.state = PlayerState::Answered;
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;
}
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();
game_data.content.retain(|x| x != &target_cons);
*color = if button_text == target_cons {
RIGHT_BUTTON.into()
} else {
WRONG_BUTTON.into()
};
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
};
border_color.0 = if button_text == selected_cons {
Color::WHITE
} else {
Color::BLACK
};
}
}
}
}
}
}
}
fn choose_constellation(
player: &mut Player,
sky: Res<Sky>,
sky: Res<Sky>, // Res to access the Sky resource
mut text_query: Query<&mut Text, With<AnswerButton>>,
mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, // Query to reset button colors
constellation_line_query : Query<(Entity, &ConstellationLine)>,
mut commands: Commands,
mut game_state: ResMut<NextState<GameState>>,
mut game_data: ResMut<GameData>,
mut game_state: ResMut<NextState<GameState>>
) {
if game_data.health == 0 {
if player.health == 0 {
info!("dead");
game_state.set(GameState::End);
}
if sky.content.len() >= 4 {
let mut rng = rand::thread_rng();
let mut selected_constellations = sky.content.clone();
selected_constellations.shuffle(&mut rng);
let constellations = &selected_constellations[0..4];
if game_data.content.len() < 4 {
game_state.set(GameState::End);
}
let target_index = rng.next_u32().rem_euclid(4) as usize;
let target_constellation = &constellations[target_index];
let mut rng = rand::thread_rng();
let mut cons_names = game_data.content.clone();
cons_names.shuffle(&mut rng);
let selected_cons_names = &cons_names[0..4];
let mut mean_pos = Vec3::ZERO;
for star in target_constellation.stars.clone() {
mean_pos += celestial_to_cartesian(star.rah, star.dec)
}
let target_rotation = Quat::from_rotation_arc(
Vec3::Z,
-mean_pos*(1.0/target_constellation.stars.len() as f32),
);
let target_index = rng.next_u32().rem_euclid(4) as usize;
let target_constellation = sky.get_constellation(&selected_cons_names[target_index]);
player.target_rotation = Some(target_rotation);
player.target_cons_name = Some(target_constellation.name.clone());
player.target_rotation = Some(constellation_center(target_constellation.clone()));
game_data.target_cons_name = Some(target_constellation.name.clone());
info!("Target constellation: {}", target_constellation.name);
info!("Target constellation: {}", target_constellation.name);
for (i, mut text) in text_query.iter_mut().enumerate() {
text.sections[0].value = constellations[i].name.clone();
}
for (i, mut text) in text_query.iter_mut().enumerate() {
text.sections[0].value = selected_cons_names[i].clone();
for (mut bg_color, mut border_color) in &mut button_query {
*bg_color = NORMAL_BUTTON.into();
*border_color = Color::BLACK.into();
}
for (entity, _line) in constellation_line_query.iter() {
commands.entity(entity).despawn();
}
player.state = PlayerState::Playing;
} else {
info!("Not enough constellations in the sky (need 4)");
}
for (mut bg_color, mut border_color) in &mut button_query {
*bg_color = NORMAL_BUTTON.into();
*border_color = Color::BLACK.into();
}
for (entity, _line) in constellation_line_query.iter() {
commands.entity(entity).despawn();
}
game_data.state = PlayerState::Playing;
}
fn constellation_center(target_constellation: Constellation) -> Quat {
let mut mean_pos = Vec3::ZERO;
for star in target_constellation.stars.clone() {
mean_pos += celestial_to_cartesian(star.rah, star.dec)
}
Quat::from_rotation_arc(
Vec3::Z,
-mean_pos*(1.0/target_constellation.stars.len() as f32),
)
}

View file

@ -2,13 +2,14 @@ use bevy::prelude::*;
use bevy::math::*;
use bevy::render::render_resource::PrimitiveTopology;
use bevy::render::render_asset::RenderAssetUsages;
use std::fs::File;
use std::io::Read;
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;
mod end_state;
mod start_state;
mod game_state;
mod explo_state;
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15);
@ -41,30 +42,11 @@ struct StarData {
name: Option<String>,
}
#[derive(Resource, Default, Clone)]
#[derive(Resource, Default)]
struct Sky {
content: Vec<Constellation>,
}
impl Sky {
fn as_string(&self) -> Vec<String> {
let mut cons_names : Vec<String> = vec![];
for cons in self.content.clone() {
cons_names.push(cons.name.clone());
}
return cons_names;
}
fn get_constellation(&self, name: &str) -> Constellation {
for cons in self.content.clone() {
if &cons.name == name {
return cons;
}
}
return self.content[0].clone();
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Constellation {
#[serde(rename = "Name")]
@ -103,36 +85,17 @@ struct MainGame;
#[derive(Component)]
struct GameOver;
#[derive(Component, Default)]
#[derive(Component)]
struct Player {
target_rotation: Option<Quat>,
dragging_pos: Option<Vec2>,
}
#[derive(Resource)]
struct GameData {
content: Vec<String>,
target_cons_name: Option<String>,
score: usize,
health: usize,
state: PlayerState,
target_cons_name: Option<String>,
}
impl Default for GameData {
fn default() -> Self {
GameData {
content: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
}
}
}
#[derive(Default, PartialEq)]
#[derive(PartialEq)]
enum PlayerState {
#[default]
Playing,
Hinted,
Answered,
@ -150,7 +113,6 @@ fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(Sky::default())
.insert_resource(GameData::default())
.init_state::<GameState>()
.add_systems(Startup, star_setup)
.add_systems(Startup, cons_setup)
@ -160,7 +122,6 @@ fn main() {
.add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>)
.add_systems(OnEnter(GameState::Game), game_state::setup)
.add_systems(Update, game_state::player_interact.run_if(in_state(GameState::Game)))
.add_systems(Update, explo_state::player_mouse_move.run_if(in_state(GameState::Game)))
.add_systems(Update, game_state::ui_buttons.run_if(in_state(GameState::Game)))
.add_systems(Update, game_state::ui_labels.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>)
@ -177,8 +138,9 @@ fn spawn_cons_lines(
sky: Res<Sky>,
target_constellation_name: String,
) {
// Create a material for the line
let line_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(0.5, 0.5, 1.0),
emissive: LinearRgba::rgb(0.5, 0.5, 1.0), // Red color for the line
..default()
});
@ -198,6 +160,7 @@ fn spawn_cons_lines(
}
}
// Create the mesh and add the vertices
let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
@ -205,7 +168,7 @@ fn spawn_cons_lines(
PbrBundle {
mesh: meshes.add(mesh),
material: line_material.clone(),
transform: Transform::default(),
transform: Transform::default(), // Position and scale for the line
..default()
},
ConstellationLine,
@ -218,12 +181,14 @@ fn star_setup(
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.insert_resource(ClearColor(Color::BLACK));
let stars = get_stars().unwrap();
//let mesh = meshes.add(Cuboid::new(star_size, star_size, star_size));
let star_mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
//let material = materials.add(Color::srgb(1.0, 1.0, 1.0));
let star_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(1.0, 1.0, 1.0),
..default()
@ -250,18 +215,12 @@ fn star_setup(
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>> {
let data = include_str!("../data/stars.json");
let mut file = File::open("data/stars.json")?;
let mut data = String::new();
file.read_to_string(&mut data)?;
let stars: Vec<StarData> = serde_json::from_str(&data).unwrap();
@ -307,7 +266,9 @@ fn cons_setup(mut sky: ResMut<Sky>) {
}
fn get_cons() -> std::io::Result<Vec<Constellation>> {
let data = include_str!("../data/constellations.json");
let mut file = File::open("data/constellations.json")?;
let mut data = String::new();
file.read_to_string(&mut data)?;
let sky_data: Vec<Constellation> = serde_json::from_str(&data).unwrap();

View file

@ -1,82 +1,101 @@
use bevy::prelude::*;
use std::f64::consts::PI;
//use bevy::input::mouse::MouseMotion;
use crate::GameState;
use crate::StartMenu;
use crate::Player;
#[derive(Component)]
struct AudioPlayer;
use crate::GameState;
use crate::GameOver;
use crate::StartMenu;
use crate::PlayerState;
pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
commands.spawn((AudioBundle {
commands.spawn(AudioBundle {
source: asset_server.load("Banjo.ogg"),
settings: PlaybackSettings::LOOP,
}, AudioPlayer));
});
info!("audio started");
}
pub fn setup(
mut commands: Commands,
) {
pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
// Create a container node that places its children (text areas) in a vertical column and centers them
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, // Center horizontally
..default()
},
..default()
};
// Create the container for the text areas
let container = commands.spawn(container_node).id();
// TextStyle for the top text (larger font)
let top_text_style = TextStyle {
font_size: 50.0,
font_size: 50.0, // Larger font size
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
..default()
};
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle {
font_size: 30.0,
font_size: 30.0, // Smaller font size
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default()
};
// TextBundle for the top text
let top_text_node = TextBundle::from_section(
"Astraea",
"Astraea", // Text for the top section
top_text_style,
);
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section(
"Press Space to Begin",
"Press Space to Begin", // Text for the bottom section
bottom_text_style,
);
// Spawn the text nodes and add them as children to the container
let top_text = commands.spawn((top_text_node, StartMenu)).id();
let bottom_text = commands.spawn((bottom_text_node, StartMenu)).id();
commands.entity(container).push_children(&[top_text, bottom_text]);
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
},
Player {
target_rotation: None,
target_cons_name: None,
score: 0,
health: 3,
state: PlayerState::Playing,
},
GameOver,
));
}
pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>,
mut game_state: ResMut<NextState<GameState>>,
mut player_query: Query<(&mut Player, &mut Transform)>,
mut player_query: Query<(&mut Player, &mut Transform)>
) {
if keys.just_pressed(KeyCode::Space) {
info!("start space");
game_state.set(GameState::Game);
}
if let Ok((_player, mut transform)) = player_query.get_single_mut() {
let mut rotation = Quat::IDENTITY;
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32);
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32);
transform.rotation *= rotation;
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32); // Rotate by 3 degrees (PI/60 radians)
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32); // Rotate by -3 degrees
transform.rotation *= rotation; // Apply the rotation
}
}