From cc23e9e08e278601bd5628331a4be8a2d5b16e06 Mon Sep 17 00:00:00 2001 From: Robert Garrett Date: Thu, 14 Aug 2025 14:50:12 -0500 Subject: [PATCH] Despawn the player when exiting the Playing state Closes #21: Despawn player ship when exiting `GameState::Playing` I've also moved the `fn despawn` utility to the lib.rs module. --- src/lib.rs | 9 +++++++++ src/widgets.rs | 9 +-------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 395c615..d26a466 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,6 +51,7 @@ impl Plugin for AsteroidPlugin { .init_resource::() .add_systems(Startup, spawn_camera) .add_systems(OnEnter(GameState::Playing), objects::spawn_player) + .add_systems(OnExit(GameState::Playing), despawn::) .add_systems( FixedUpdate, ( @@ -84,6 +85,14 @@ impl Plugin for AsteroidPlugin { } } +/// Despawns entities matching the generic argument. Intended to remove UI +/// elements. +pub(crate) fn despawn(mut commands: Commands, to_despawn: Query>) { + for entity in to_despawn { + commands.entity(entity).despawn(); + } +} + /// The game's main state tracking mechanism, registered with Bevy as a [`State`](`bevy::prelude::State`). #[derive(Clone, Debug, Eq, Hash, PartialEq, States)] pub enum GameState { diff --git a/src/widgets.rs b/src/widgets.rs index 6bee726..e6fc026 100644 --- a/src/widgets.rs +++ b/src/widgets.rs @@ -3,6 +3,7 @@ use std::ops::DerefMut; use crate::{ GameState, config::{UI_BUTTON_HOVERED, UI_BUTTON_NORMAL, UI_BUTTON_PRESSED}, + despawn, resources::{Lives, Score}, }; @@ -105,14 +106,6 @@ struct CountdownText; #[derive(Component)] struct CountdownBar; -/// Despawns entities matching the generic argument. Intended to remove UI -/// elements. -fn despawn(mut commands: Commands, to_despawn: Query>) { - for entity in to_despawn { - commands.entity(entity).despawn(); - } -} - /// Utility function for creating a standard button. fn button_bundle(text: &str) -> impl Bundle { (