Files
down_into_the_void/src/score.rs
T
2026-09-19 11:43:07 +02:00

72 lines
1.8 KiB
Rust

use bevy::prelude::*;
use crate::{
game_state::GameState,
player::{Player, START_POSITION, move_player},
};
#[derive(Resource, Default)]
pub struct Depth(pub f32);
// Update depth of the player
fn update_depth(mut depth: ResMut<Depth>, player: Single<&Transform, With<Player>>) {
depth.0 = START_POSITION.y - player.translation.y;
}
#[derive(Component)]
pub struct DepthText;
// Display the initial text of the depth (Score)
fn spawn_depth_text(mut commands: Commands) {
commands.spawn((
Text::new("0"),
TextFont {
font_size: FontSize::Px(50.0),
..default()
},
TextColor(Color::WHITE),
Node {
position_type: PositionType::Absolute,
top: Val::Px(20.0),
left: Val::Px(20.0),
..default()
},
DepthText,
));
}
// Update depth score text
fn update_depth_text(
mut commands: Commands,
depth: Res<Depth>,
texts: Query<&mut Text, With<DepthText>>,
) {
for mut text in texts {
text.0 = format!("Score: {}", depth.0);
}
}
fn cleanup_score(mut commands: Commands, entities: Query<Entity, With<DepthText>>) {
for entity in entities {
commands.entity(entity).despawn();
}
}
pub struct ScorePlugin;
impl Plugin for ScorePlugin {
fn build(&self, app: &mut App) {
app.init_resource::<Depth>()
.add_systems(OnEnter(GameState::InGame), spawn_depth_text)
.add_systems(
Update,
(
update_depth_text.after(spawn_depth_text),
update_depth.after(move_player),
)
.run_if(in_state(GameState::InGame)),
)
.add_systems(OnExit(GameState::InGame), cleanup_score);
}
}