4 Commits

Author SHA1 Message Date
cf9825fcc3 Fix: Starting game from GUI runs "get ready" timer
All checks were successful
Basic checks / Basic build-and-test supertask (push) Successful in 7m14s
Closes #23: Main menu's start button doesn't run the get-ready timer

I made the start button go directly to `GameState::Playing`, which is
not actually the right state for beginning a new game. Swap the states
and everything works again.
2025-08-14 14:39:24 -05:00
708f514582 Implement a proper gun fire-rate mechanism
There is now a `Weapon` component which is just a timer for the gun's
fire rate. It is ticked every frame, clamping at the "ready" state (0
time remaining).

The ship spawns with this thing, and the `input_ship_shoot` system has
been updated to use it.
2025-08-14 14:34:22 -05:00
0a7ffcfa0a Add reflection & debug inspector stuff to Score 2025-08-14 13:14:32 -05:00
40ee042b53 Implement the HUD for real
Now it works!... but it runs every single frame, probably causing a
bunch of unnecessary text rendering and UI layout operations. I'll have
to come back and make it event-based at some point.
2025-08-14 13:07:25 -05:00
5 changed files with 89 additions and 18 deletions

View File

@@ -13,6 +13,7 @@ pub(crate) const BACKGROUND_COLOR: Color = Color::srgb(0.3, 0.3, 0.3);
pub(crate) const PLAYER_SHIP_COLOR: Color = Color::srgb(1.0, 1.0, 1.0);
pub(crate) const SHIP_THRUSTER_COLOR_ACTIVE: Color = Color::srgb(1.0, 0.2, 0.2);
pub(crate) const SHIP_THRUSTER_COLOR_INACTIVE: Color = Color::srgb(0.5, 0.5, 0.5);
pub(crate) const SHIP_FIRE_RATE: f32 = 3.0; // in bullets-per-second
pub(crate) const ASTEROID_SMALL_COLOR: Color = Color::srgb(1.0, 0., 0.);
pub(crate) const BULLET_COLOR: Color = Color::srgb(0.0, 0.1, 0.9);
// TODO: asteroid medium & large

View File

@@ -16,7 +16,7 @@ use crate::config::{
SHIP_THRUSTER_COLOR_INACTIVE,
};
use crate::machinery::AsteroidSpawner;
use crate::objects::{Bullet, Ship};
use crate::objects::{Bullet, Ship, Weapon};
use crate::physics::AngularVelocity;
use bevy::prelude::*;
@@ -37,6 +37,7 @@ impl Plugin for AsteroidPlugin {
widgets::PluginGameMenu,
widgets::PluginGameOver,
widgets::PluginGetReady,
widgets::PluginGameHud,
RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(10.0),
RapierDebugRenderPlugin::default(),
))
@@ -45,13 +46,11 @@ impl Plugin for AsteroidPlugin {
.insert_resource(Lives(3))
.register_type::<Lives>()
.insert_resource(Score(0))
.register_type::<Score>()
.insert_resource(AsteroidSpawner::new())
.init_resource::<GameAssets>()
.add_systems(Startup, spawn_camera)
.add_systems(
OnEnter(GameState::Playing),
(objects::spawn_player, widgets::spawn_ui),
)
.add_systems(OnEnter(GameState::Playing), objects::spawn_player)
.add_systems(
FixedUpdate,
(
@@ -161,19 +160,25 @@ fn input_ship_rotation(
/// tick those timers. Maybe this system?
fn input_ship_shoot(
keyboard_input: Res<ButtonInput<KeyCode>>,
ship: Single<(&Transform, &physics::Velocity), With<Ship>>,
ship: Single<(&Transform, &physics::Velocity, &mut Weapon), With<Ship>>,
game_assets: Res<GameAssets>,
mut commands: Commands,
time: Res<Time>,
) {
let (ship_pos, ship_vel) = *ship;
let (ship_pos, ship_vel, mut weapon) = ship.into_inner();
// Derive bullet velocity, add to the ship's velocity
let bullet_vel = (ship_pos.rotation * Vec3::X).xy() * BULLET_SPEED;
let bullet_vel = bullet_vel + ship_vel.0;
// Tick the timer so the cooldown eventually finishes. Once it does, the
// value will clamp at 0. The weapon is now ready.
weapon.tick(time.delta());
// If the weapon is ready and the player presses the trigger,
// spawn a bullet & reset the timer.
if weapon.finished() && keyboard_input.pressed(KeyCode::Space) {
weapon.reset();
// Derive bullet velocity, add to the ship's velocity
let bullet_vel = (ship_pos.rotation * Vec3::X).xy() * BULLET_SPEED;
let bullet_vel = bullet_vel + ship_vel.0;
// TODO: create a timer for the gun fire rate.
// For now, spawn one for each press of the spacebar.
if keyboard_input.just_pressed(KeyCode::Space) {
commands.spawn((
Bullet,
Collider::ball(0.2),

View File

@@ -22,7 +22,7 @@ use bevy_rapier2d::prelude::{ActiveCollisionTypes, ActiveEvents, Collider, Senso
use crate::{
AngularVelocity, GameAssets, GameState, Lives,
config::ASTEROID_LIFETIME,
config::{ASTEROID_LIFETIME, SHIP_FIRE_RATE},
events::{AsteroidDestroy, BulletDestroy, ShipDestroy, SpawnAsteroid},
machinery::Lifetime,
physics::{Velocity, Wrapping},
@@ -55,6 +55,10 @@ impl AsteroidSize {
#[derive(Component)]
pub struct Ship;
/// The ship's gun (is just a timer)
#[derive(Component, Deref, DerefMut)]
pub struct Weapon(Timer);
/// Marker component for bullets.
#[derive(Component)]
pub struct Bullet;
@@ -144,6 +148,7 @@ pub fn spawn_player(mut commands: Commands, game_assets: Res<GameAssets>) {
ActiveEvents::COLLISION_EVENTS,
ActiveCollisionTypes::STATIC_STATIC,
Ship,
Weapon(Timer::from_seconds(1.0 / SHIP_FIRE_RATE, TimerMode::Once)),
Wrapping,
Velocity(Vec2::ZERO),
AngularVelocity(0.0),

View File

@@ -22,7 +22,8 @@ use crate::{
SHIP_THRUSTER_COLOR_INACTIVE, config::WINDOW_SIZE,
};
#[derive(Resource, Debug, Deref, Clone, Copy)]
#[derive(InspectorOptions, Reflect, Resource, Debug, Deref, Clone, Copy)]
#[reflect(Resource, InspectorOptions)]
pub struct Score(pub i32);
impl From<Score> for String {

View File

@@ -1,3 +1,5 @@
use std::ops::DerefMut;
use crate::{
GameState,
config::{UI_BUTTON_HOVERED, UI_BUTTON_NORMAL, UI_BUTTON_PRESSED},
@@ -38,6 +40,17 @@ impl Plugin for PluginGetReady {
}
}
/// Plugin for the in-game HUD
pub struct PluginGameHud;
impl Plugin for PluginGameHud {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(GameState::Playing), spawn_ui)
.add_systems(OnExit(GameState::Playing), despawn::<MarkerHUD>)
.add_systems(Update, (operate_ui).run_if(in_state(GameState::Playing)));
}
}
/// Plugin for the game-over screen
pub struct PluginGameOver;
@@ -65,6 +78,10 @@ struct OnReadySetGo;
#[derive(Component)]
struct MarkerGameOver;
/// Marker for things on the HUD (the in-game UI elements)
#[derive(Component)]
struct MarkerHUD;
/// Action specifier for the game-over menu's buttons.
///
/// Attach this component to a button and [`PluginGameOver`] will use it to
@@ -267,7 +284,7 @@ fn operate_buttons(
game_state.set(GameState::TitleScreen);
}
ButtonMenuAction::StartGame => {
game_state.set(GameState::Playing);
game_state.set(GameState::GetReady);
}
ButtonMenuAction::Quit => {
app_exit_events.write(AppExit::Success);
@@ -294,8 +311,50 @@ fn handle_spacebar(input: Res<ButtonInput<KeyCode>>, mut game_state: ResMut<Next
}
pub fn spawn_ui(mut commands: Commands, score: Res<Score>, lives: Res<Lives>) {
let score = score.0;
let lives = lives.0;
commands.spawn((
Text::new(format!("Score: {score:?} | Lives: {lives:?}")),
TextFont::from_font_size(25.0),
MarkerHUD,
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Start,
justify_content: JustifyContent::SpaceBetween,
padding: UiRect::all(Val::Px(5.0)),
..default()
},
children![
(
Text::new(format!("Score: {score}")),
TextFont::from_font_size(25.0),
TextShadow::default(),
),
(
Text::new(format!("Lives: {lives}")),
TextFont::from_font_size(25.0),
TextShadow::default(),
)
],
));
}
/// Updates the HUD with the current score & life count
///
/// TODO: some kind of event-based thing. Touching the text nodes every frame
/// seems expensive.
fn operate_ui(
mut query: Single<(&Node, &Children), With<MarkerHUD>>,
mut text_query: Query<&mut Text>,
lives: Res<Lives>,
score: Res<Score>,
) {
let (_node, children) = query.deref_mut();
let score = score.0;
let lives = lives.0;
// TODO: Something smarter than `unwrap()`
let mut score_text = text_query.get_mut(children[0]).unwrap();
**score_text = format!("Score: {score}");
let mut lives_text = text_query.get_mut(children[1]).unwrap();
**lives_text = format!("Lives: {lives}");
}