Compare commits
16 Commits
804186ea2f
...
70f2313766
| Author | SHA1 | Date | |
|---|---|---|---|
| 70f2313766 | |||
| 58bbc1e614 | |||
| 79679759c5 | |||
| 0e517de419 | |||
| cb2b57449a | |||
| 9a262fcffc | |||
| 34ee2fcc7d | |||
| 93da225636 | |||
| cd194e2dbf | |||
| 1369a3092f | |||
| 619037dab0 | |||
| c1b69c412a | |||
| d8a83b77c2 | |||
| f5ff7c8779 | |||
| f4484f759f | |||
| 571b910945 |
184
src/asteroids.rs
184
src/asteroids.rs
@@ -1,184 +0,0 @@
|
||||
//! This is the module containing all the rock-related things.
|
||||
//! Not... not the whole game.
|
||||
|
||||
use bevy_rapier2d::prelude::*;
|
||||
use rand::{Rng, SeedableRng};
|
||||
use std::time::Duration;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{
|
||||
GameAssets, Lifetime, WorldSize, config::ASTEROID_LIFETIME, event::AsteroidDestroy,
|
||||
physics::Velocity,
|
||||
};
|
||||
|
||||
#[derive(Component, Deref, DerefMut)]
|
||||
pub struct Asteroid(AsteroidSize);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum AsteroidSize {
|
||||
Small,
|
||||
Medium,
|
||||
Large,
|
||||
}
|
||||
|
||||
impl AsteroidSize {
|
||||
fn next(&self) -> Option<Self> {
|
||||
match self {
|
||||
AsteroidSize::Small => None,
|
||||
AsteroidSize::Medium => Some(AsteroidSize::Small),
|
||||
AsteroidSize::Large => Some(AsteroidSize::Medium),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct AsteroidSpawner {
|
||||
rng: std::sync::Mutex<rand::rngs::StdRng>,
|
||||
timer: Timer,
|
||||
// TODO: Configurables?
|
||||
// - interval
|
||||
// - density
|
||||
// - size distribution
|
||||
}
|
||||
|
||||
impl AsteroidSpawner {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
rng: std::sync::Mutex::new(rand::rngs::StdRng::from_seed(crate::config::RNG_SEED)),
|
||||
timer: Timer::new(Duration::from_secs(3), TimerMode::Repeating),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Event)]
|
||||
pub struct SpawnAsteroid {
|
||||
pos: Vec2,
|
||||
vel: Vec2,
|
||||
size: AsteroidSize,
|
||||
}
|
||||
|
||||
/// Update the asteroid spawn timer and spawn any asteroids
|
||||
/// that are due this frame.
|
||||
pub fn tick_asteroid_manager(
|
||||
mut events: EventWriter<SpawnAsteroid>,
|
||||
mut spawner: ResMut<AsteroidSpawner>,
|
||||
time: Res<Time>,
|
||||
play_area: Res<WorldSize>,
|
||||
) {
|
||||
spawner.timer.tick(time.delta());
|
||||
if spawner.timer.just_finished() {
|
||||
let mut rng = spawner
|
||||
.rng
|
||||
.lock()
|
||||
.expect("Expected to acquire lock on the AsteroidSpawner's RNG field.");
|
||||
|
||||
// Use polar coordinate to decide where the asteroid will spawn
|
||||
// Theta will be random between 0 to 2pi
|
||||
let spawn_angle = rng.random_range(0.0..(std::f32::consts::PI * 2.0));
|
||||
// Rho will be the radius of a circle bordering the viewport, multiplied by 1.2
|
||||
// TODO: Use view diagonal to get a minimally sized circle around the play area
|
||||
let spawn_distance = play_area.width.max(play_area.height) / 2.0;
|
||||
|
||||
// Convert polar to Cartesian, use as position
|
||||
let pos = Vec2::new(
|
||||
spawn_distance * spawn_angle.cos(),
|
||||
spawn_distance * spawn_angle.sin(),
|
||||
);
|
||||
|
||||
// Right now, I'm thinking I can use the opposite signs attached to the position Vec components.
|
||||
// pos.x == -100, then vel.x = + <random>
|
||||
// pos.x == 100, then vel.x = - <random>
|
||||
// etc,
|
||||
let mut vel = Vec2::new(rng.random_range(0.0..100.0), rng.random_range(0.0..100.0));
|
||||
if pos.x > 0.0 {
|
||||
vel.x *= -1.0;
|
||||
}
|
||||
if pos.y > 0.0 {
|
||||
vel.y *= -1.0;
|
||||
}
|
||||
|
||||
let size = match rng.random_range(0..=2) {
|
||||
0 => AsteroidSize::Small,
|
||||
1 => AsteroidSize::Medium,
|
||||
2 => AsteroidSize::Large,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
events.write(SpawnAsteroid { pos, vel, size });
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility function to spawn a single asteroid of a given type
|
||||
/// TODO: convert to an event listener monitoring for "spawn asteroid" events
|
||||
/// from the `fn tick_asteroid_manager(...)` system.
|
||||
pub fn spawn_asteroid(
|
||||
mut events: EventReader<SpawnAsteroid>,
|
||||
mut commands: Commands,
|
||||
game_assets: Res<GameAssets>,
|
||||
) {
|
||||
for spawn in events.read() {
|
||||
let (mesh, material) = match spawn.size {
|
||||
AsteroidSize::Small => game_assets.asteroid_small(),
|
||||
AsteroidSize::Medium => game_assets.asteroid_medium(),
|
||||
AsteroidSize::Large => game_assets.asteroid_large(),
|
||||
};
|
||||
|
||||
let collider_radius = match spawn.size {
|
||||
AsteroidSize::Small => 10.0,
|
||||
AsteroidSize::Medium => 20.0,
|
||||
AsteroidSize::Large => 40.0,
|
||||
};
|
||||
|
||||
commands.spawn((
|
||||
Asteroid(spawn.size),
|
||||
Collider::ball(collider_radius),
|
||||
Sensor,
|
||||
Transform::from_translation(spawn.pos.extend(0.0)),
|
||||
Velocity(spawn.vel),
|
||||
Mesh2d(mesh),
|
||||
MeshMaterial2d(material),
|
||||
Lifetime(Timer::from_seconds(ASTEROID_LIFETIME, TimerMode::Once)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Event listener for asteroid destruction events. Shrinks and multiplies
|
||||
/// asteroids until they vanish.
|
||||
///
|
||||
/// - Large -> 2x Medium
|
||||
/// - Medium -> 2x Small
|
||||
/// - Small -> (despawned)
|
||||
///
|
||||
/// The velocity of the child asteroids is scattered somewhat, as if they were
|
||||
/// explosively pushed apart.
|
||||
pub fn split_asteroids(
|
||||
mut destroy_events: EventReader<AsteroidDestroy>,
|
||||
mut respawn_events: EventWriter<SpawnAsteroid>,
|
||||
mut commands: Commands,
|
||||
query: Query<(&Transform, &Asteroid, &Velocity)>,
|
||||
) {
|
||||
for event in destroy_events.read() {
|
||||
if let Ok((transform, rock, velocity)) = query.get(event.0) {
|
||||
let next_size = rock.0.next();
|
||||
if let Some(size) = next_size {
|
||||
let pos = transform.translation.xy();
|
||||
let left_offset = Vec2::from_angle(0.4);
|
||||
let right_offset = Vec2::from_angle(-0.4);
|
||||
respawn_events.write(SpawnAsteroid {
|
||||
pos,
|
||||
vel: left_offset.rotate(velocity.0),
|
||||
size,
|
||||
});
|
||||
respawn_events.write(SpawnAsteroid {
|
||||
pos,
|
||||
vel: right_offset.rotate(velocity.0),
|
||||
size,
|
||||
});
|
||||
}
|
||||
// Always despawn the asteroid. New ones (may) be spawned in it's
|
||||
// place, but this one is gone.
|
||||
commands.entity(event.0).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
21
src/event.rs
21
src/event.rs
@@ -1,21 +0,0 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
/// Signals that the player's ship has been destroyed.
|
||||
/// Used when the player collides with an asteroid.
|
||||
#[derive(Event)]
|
||||
pub(crate) struct ShipDestroy;
|
||||
|
||||
/// Signals that a particular asteroid has been destroyed.
|
||||
/// Used to split (or vanish) an asteroid when a bullet strikes it.
|
||||
#[derive(Event)]
|
||||
pub(crate) struct AsteroidDestroy(pub Entity);
|
||||
|
||||
// TODO: BulletDestroy
|
||||
// Which depends on the still-pending Bullet component creation.
|
||||
|
||||
/// Signals that a particular bullet has been destroyed.
|
||||
/// Used to despawn the bullet after it strikes an Asteroid.
|
||||
///
|
||||
/// TODO: Maybe use it for lifetime expiration (which is also a TODO item).
|
||||
#[derive(Event)]
|
||||
pub(crate) struct BulletDestroy(pub Entity);
|
||||
36
src/events.rs
Normal file
36
src/events.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::objects::AsteroidSize;
|
||||
|
||||
/// Signals that the player's ship has been destroyed.
|
||||
///
|
||||
/// Produced by the [`fn collision_listener(...)`](`crate::physics::collision_listener`)
|
||||
/// system when the player collides with an asteroid. They are consumed by [`fn ship_impact_listener(...)`](`crate::objects::ship_impact_listener`).
|
||||
#[derive(Event)]
|
||||
pub(crate) struct ShipDestroy;
|
||||
|
||||
/// Signals that a particular asteroid has been destroyed.
|
||||
///
|
||||
/// Produced by the [`fn collision_listener(...)`](`crate::physics::collision_listener`)
|
||||
/// system when bullets contact asteroids. It is consumed by [`fn split_asteroid(...)`](`crate::objects::spawn_asteroid`)
|
||||
/// system, which re-emits [spawn events](`SpawnAsteroid`).
|
||||
#[derive(Event)]
|
||||
pub(crate) struct AsteroidDestroy(pub Entity);
|
||||
|
||||
/// Signals that an asteroid needs to be spawned and provides the parameters
|
||||
/// for that action.
|
||||
///
|
||||
/// Produced by the [`tick_asteroid_manager(...)`](`crate::machinery::tick_asteroid_manager`)
|
||||
/// system and consumed by the [`spawn_asteroid(...)`](`crate::objects::spawn_asteroid`) system.
|
||||
#[derive(Event)]
|
||||
pub struct SpawnAsteroid {
|
||||
pub pos: Vec2,
|
||||
pub vel: Vec2,
|
||||
pub size: AsteroidSize,
|
||||
}
|
||||
|
||||
/// Signals that a particular bullet has been destroyed (after it strikes an Asteroid).
|
||||
///
|
||||
/// TODO: Maybe use it for lifetime expiration (which is also a TODO item).
|
||||
#[derive(Event)]
|
||||
pub(crate) struct BulletDestroy(pub Entity);
|
||||
231
src/lib.rs
231
src/lib.rs
@@ -1,36 +1,36 @@
|
||||
mod asteroids;
|
||||
pub mod config;
|
||||
mod event;
|
||||
mod events;
|
||||
mod machinery;
|
||||
mod objects;
|
||||
mod physics;
|
||||
mod preparation_widget;
|
||||
mod ship;
|
||||
mod title_screen;
|
||||
mod resources;
|
||||
mod widgets;
|
||||
|
||||
use crate::asteroids::{Asteroid, AsteroidSpawner};
|
||||
use crate::config::{
|
||||
ASTEROID_SMALL_COLOR, BACKGROUND_COLOR, BULLET_COLOR, BULLET_LIFETIME, BULLET_SPEED,
|
||||
PLAYER_SHIP_COLOR, SHIP_ROTATION, SHIP_THRUST, SHIP_THRUSTER_COLOR_ACTIVE,
|
||||
SHIP_THRUSTER_COLOR_INACTIVE, WINDOW_SIZE,
|
||||
};
|
||||
use crate::machinery::AsteroidSpawner;
|
||||
use crate::objects::{Bullet, Ship};
|
||||
use crate::physics::AngularVelocity;
|
||||
use crate::ship::{Bullet, Ship};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_inspector_egui::InspectorOptions;
|
||||
use bevy_inspector_egui::prelude::ReflectInspectorOptions;
|
||||
use bevy_rapier2d::{
|
||||
plugin::{NoUserData, RapierPhysicsPlugin},
|
||||
prelude::*,
|
||||
render::RapierDebugRenderPlugin,
|
||||
};
|
||||
use machinery::Lifetime;
|
||||
use resources::{GameAssets, Lives, Score, WorldSize};
|
||||
|
||||
pub struct AsteroidPlugin;
|
||||
|
||||
impl Plugin for AsteroidPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_plugins((
|
||||
title_screen::GameMenuPlugin,
|
||||
preparation_widget::preparation_widget_plugin,
|
||||
widgets::GameMenuPlugin,
|
||||
widgets::preparation_widget_plugin,
|
||||
RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(10.0),
|
||||
RapierDebugRenderPlugin::default(),
|
||||
))
|
||||
@@ -45,7 +45,10 @@ impl Plugin for AsteroidPlugin {
|
||||
.insert_resource(AsteroidSpawner::new())
|
||||
.init_resource::<GameAssets>()
|
||||
.add_systems(Startup, spawn_camera)
|
||||
.add_systems(OnEnter(GameState::Playing), (ship::spawn_player, spawn_ui))
|
||||
.add_systems(
|
||||
OnEnter(GameState::Playing),
|
||||
(objects::spawn_player, widgets::spawn_ui),
|
||||
)
|
||||
.add_systems(
|
||||
FixedUpdate,
|
||||
(
|
||||
@@ -53,15 +56,15 @@ impl Plugin for AsteroidPlugin {
|
||||
input_ship_rotation,
|
||||
input_ship_shoot,
|
||||
physics::wrap_entities,
|
||||
asteroids::tick_asteroid_manager,
|
||||
asteroids::spawn_asteroid.after(asteroids::tick_asteroid_manager),
|
||||
asteroids::split_asteroids,
|
||||
ship::bullet_impact_listener,
|
||||
ship::ship_impact_listener,
|
||||
collision_listener,
|
||||
machinery::tick_asteroid_manager,
|
||||
objects::spawn_asteroid.after(machinery::tick_asteroid_manager),
|
||||
objects::split_asteroids,
|
||||
objects::bullet_impact_listener,
|
||||
objects::ship_impact_listener,
|
||||
physics::collision_listener,
|
||||
// TODO: Remove debug printing
|
||||
debug_collision_event_printer,
|
||||
tick_lifetimes,
|
||||
machinery::tick_lifetimes,
|
||||
)
|
||||
.run_if(in_state(GameState::Playing)),
|
||||
)
|
||||
@@ -73,10 +76,10 @@ impl Plugin for AsteroidPlugin {
|
||||
)
|
||||
.run_if(in_state(GameState::Playing)),
|
||||
)
|
||||
.add_event::<asteroids::SpawnAsteroid>()
|
||||
.add_event::<event::AsteroidDestroy>()
|
||||
.add_event::<event::ShipDestroy>()
|
||||
.add_event::<event::BulletDestroy>();
|
||||
.add_event::<events::SpawnAsteroid>()
|
||||
.add_event::<events::AsteroidDestroy>()
|
||||
.add_event::<events::ShipDestroy>()
|
||||
.add_event::<events::BulletDestroy>();
|
||||
app.insert_state(GameState::Playing);
|
||||
}
|
||||
}
|
||||
@@ -87,69 +90,6 @@ fn debug_collision_event_printer(mut collision_events: EventReader<CollisionEven
|
||||
}
|
||||
}
|
||||
|
||||
/// The collision event routing system.
|
||||
///
|
||||
/// When a `CollisionEvent` occurrs, this system checks which things collided
|
||||
/// and emits secondary events accordignly.
|
||||
///
|
||||
/// | Objects | Response |
|
||||
/// |-|-|
|
||||
/// | Ship & Asteroid | emits event [`ShipDestroy`](`crate::event::ShipDestroy`) |
|
||||
/// | Asteroid & Bullet | emits event [`AsteroidDestroy`](`crate::event::AsteroidDestroy`) |
|
||||
/// | Asteroid & Asteroid | Nothing. Asteroids won't collide with each other |
|
||||
/// | Bullet & Bullet | Nothing. Bullets won't collide with each other (and probably can't under normal gameplay conditions) |
|
||||
/// | Bullet & Ship | Nothing. The player shouldn't be able to shoot themselves (and the Flying Saucer hasn't been impl.'d, so it's bullets don't count) |
|
||||
fn collision_listener(
|
||||
mut collisions: EventReader<CollisionEvent>,
|
||||
mut ship_writer: EventWriter<event::ShipDestroy>,
|
||||
mut asteroid_writer: EventWriter<event::AsteroidDestroy>,
|
||||
mut bullet_writer: EventWriter<event::BulletDestroy>,
|
||||
player: Single<Entity, With<Ship>>,
|
||||
bullets: Query<&Bullet>,
|
||||
rocks: Query<&Asteroid>,
|
||||
) {
|
||||
for event in collisions.read() {
|
||||
if let CollisionEvent::Started(one, two, _flags) = event {
|
||||
// Valid collisions are:
|
||||
//
|
||||
// - Ship & Asteroid
|
||||
// - Bullet & Asteroid
|
||||
//
|
||||
// Asteroids don't collide with each other, bullets don't collide
|
||||
// with each other, and bullets don't collide with the player ship.
|
||||
|
||||
// Option 1: Ship & Asteroid
|
||||
if *one == *player {
|
||||
if rocks.contains(*two) {
|
||||
// player-asteroid collision
|
||||
dbg!("Writing ShipDestroy event");
|
||||
ship_writer.write(event::ShipDestroy);
|
||||
} // else, we don't care
|
||||
} else if *two == *player {
|
||||
if rocks.contains(*one) {
|
||||
dbg!("Writing ShipDestroy event");
|
||||
ship_writer.write(event::ShipDestroy);
|
||||
}
|
||||
}
|
||||
|
||||
// Option 2: Bullet & Asteroid
|
||||
if bullets.contains(*one) {
|
||||
if rocks.contains(*two) {
|
||||
dbg!("Writing AsteroidDestroy & BulletDestroy events");
|
||||
asteroid_writer.write(event::AsteroidDestroy(*two));
|
||||
bullet_writer.write(event::BulletDestroy(*one));
|
||||
}
|
||||
} else if rocks.contains(*one) {
|
||||
if bullets.contains(*two) {
|
||||
dbg!("Writing AsteroidDestroy & BulletDestroy events");
|
||||
asteroid_writer.write(event::AsteroidDestroy(*one));
|
||||
bullet_writer.write(event::BulletDestroy(*two));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq, States)]
|
||||
pub enum GameState {
|
||||
TitleScreen, // Program is started. Present title screen and await user start
|
||||
@@ -158,107 +98,6 @@ pub enum GameState {
|
||||
GameOver, // Game has ended. Present game over dialogue and await user restart
|
||||
}
|
||||
|
||||
#[derive(Resource, Debug, Deref, Clone, Copy)]
|
||||
struct Score(i32);
|
||||
|
||||
impl From<Score> for String {
|
||||
fn from(value: Score) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
struct Lifetime(Timer);
|
||||
|
||||
#[derive(InspectorOptions, Reflect, Resource, Debug, Deref, Clone, Copy)]
|
||||
#[reflect(Resource, InspectorOptions)]
|
||||
struct Lives(i32);
|
||||
|
||||
impl From<Lives> for String {
|
||||
fn from(value: Lives) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct WorldSize {
|
||||
width: f32,
|
||||
height: f32,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
struct GameAssets {
|
||||
meshes: [Handle<Mesh>; 5],
|
||||
materials: [Handle<ColorMaterial>; 7],
|
||||
}
|
||||
|
||||
impl GameAssets {
|
||||
fn ship(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[0].clone(), self.materials[0].clone())
|
||||
}
|
||||
|
||||
// The thruster mesh is actually just the ship mesh
|
||||
fn thruster_mesh(&self) -> Handle<Mesh> {
|
||||
self.meshes[0].clone()
|
||||
}
|
||||
|
||||
// TODO: Look into parameterizing the material
|
||||
// A shader uniform should be able to do this, but I don't know how to
|
||||
// load those in Bevy.
|
||||
fn thruster_mat_inactive(&self) -> Handle<ColorMaterial> {
|
||||
self.materials[1].clone()
|
||||
}
|
||||
|
||||
fn thruster_mat_active(&self) -> Handle<ColorMaterial> {
|
||||
self.materials[2].clone()
|
||||
}
|
||||
|
||||
fn asteroid_small(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[1].clone(), self.materials[1].clone())
|
||||
}
|
||||
|
||||
fn asteroid_medium(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[2].clone(), self.materials[2].clone())
|
||||
}
|
||||
|
||||
fn asteroid_large(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[3].clone(), self.materials[3].clone())
|
||||
}
|
||||
|
||||
fn bullet(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[4].clone(), self.materials[6].clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for GameAssets {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let mut world_meshes = world.resource_mut::<Assets<Mesh>>();
|
||||
let meshes = [
|
||||
world_meshes.add(Triangle2d::new(
|
||||
Vec2::new(0.5, 0.0),
|
||||
Vec2::new(-0.5, 0.45),
|
||||
Vec2::new(-0.5, -0.45),
|
||||
)),
|
||||
world_meshes.add(Circle::new(10.0)),
|
||||
world_meshes.add(Circle::new(20.0)),
|
||||
world_meshes.add(Circle::new(40.0)),
|
||||
world_meshes.add(Circle::new(0.2)),
|
||||
];
|
||||
let mut world_materials = world.resource_mut::<Assets<ColorMaterial>>();
|
||||
let materials = [
|
||||
world_materials.add(PLAYER_SHIP_COLOR),
|
||||
world_materials.add(SHIP_THRUSTER_COLOR_INACTIVE),
|
||||
world_materials.add(SHIP_THRUSTER_COLOR_ACTIVE),
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
// TODO: asteroid medium and large colors
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
world_materials.add(BULLET_COLOR),
|
||||
];
|
||||
GameAssets { meshes, materials }
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_camera(mut commands: Commands) {
|
||||
commands.spawn(Camera2d);
|
||||
}
|
||||
@@ -334,7 +173,7 @@ fn input_ship_shoot(
|
||||
// For now, spawn one for each press of the spacebar.
|
||||
if keyboard_input.just_pressed(KeyCode::Space) {
|
||||
commands.spawn((
|
||||
ship::Bullet,
|
||||
Bullet,
|
||||
Collider::ball(0.2),
|
||||
Sensor,
|
||||
ActiveEvents::COLLISION_EVENTS,
|
||||
@@ -347,19 +186,3 @@ fn input_ship_shoot(
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_ui(mut commands: Commands, score: Res<Score>, lives: Res<Lives>) {
|
||||
commands.spawn((
|
||||
Text::new(format!("Score: {score:?} | Lives: {lives:?}")),
|
||||
TextFont::from_font_size(25.0),
|
||||
));
|
||||
}
|
||||
|
||||
fn tick_lifetimes(mut commands: Commands, time: Res<Time>, query: Query<(Entity, &mut Lifetime)>) {
|
||||
for (e, mut life) in query {
|
||||
life.0.tick(time.delta());
|
||||
if life.0.just_finished() {
|
||||
commands.entity(e).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
94
src/machinery.rs
Normal file
94
src/machinery.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! These are Systems that power the main game mechanics (and some misc items to support them)
|
||||
|
||||
use rand::{Rng, SeedableRng};
|
||||
use std::time::Duration;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
use crate::{WorldSize, events::SpawnAsteroid, objects::AsteroidSize};
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct AsteroidSpawner {
|
||||
rng: std::sync::Mutex<rand::rngs::StdRng>,
|
||||
timer: Timer,
|
||||
// TODO: Configurables?
|
||||
// - interval
|
||||
// - density
|
||||
// - size distribution
|
||||
}
|
||||
|
||||
impl AsteroidSpawner {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
rng: std::sync::Mutex::new(rand::rngs::StdRng::from_seed(crate::config::RNG_SEED)),
|
||||
timer: Timer::new(Duration::from_secs(3), TimerMode::Repeating),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the asteroid spawn timer and spawn any asteroids
|
||||
/// that are due this frame.
|
||||
pub fn tick_asteroid_manager(
|
||||
mut events: EventWriter<SpawnAsteroid>,
|
||||
mut spawner: ResMut<AsteroidSpawner>,
|
||||
time: Res<Time>,
|
||||
play_area: Res<WorldSize>,
|
||||
) {
|
||||
spawner.timer.tick(time.delta());
|
||||
if spawner.timer.just_finished() {
|
||||
let mut rng = spawner
|
||||
.rng
|
||||
.lock()
|
||||
.expect("Expected to acquire lock on the AsteroidSpawner's RNG field.");
|
||||
|
||||
// Use polar coordinate to decide where the asteroid will spawn
|
||||
// Theta will be random between 0 to 2pi
|
||||
let spawn_angle = rng.random_range(0.0..(std::f32::consts::PI * 2.0));
|
||||
// Rho will be the radius of a circle bordering the viewport, multiplied by 1.2
|
||||
// TODO: Use view diagonal to get a minimally sized circle around the play area
|
||||
let spawn_distance = play_area.width.max(play_area.height) / 2.0;
|
||||
|
||||
// Convert polar to Cartesian, use as position
|
||||
let pos = Vec2::new(
|
||||
spawn_distance * spawn_angle.cos(),
|
||||
spawn_distance * spawn_angle.sin(),
|
||||
);
|
||||
|
||||
// Right now, I'm thinking I can use the opposite signs attached to the position Vec components.
|
||||
// pos.x == -100, then vel.x = + <random>
|
||||
// pos.x == 100, then vel.x = - <random>
|
||||
// etc,
|
||||
let mut vel = Vec2::new(rng.random_range(0.0..100.0), rng.random_range(0.0..100.0));
|
||||
if pos.x > 0.0 {
|
||||
vel.x *= -1.0;
|
||||
}
|
||||
if pos.y > 0.0 {
|
||||
vel.y *= -1.0;
|
||||
}
|
||||
|
||||
let size = match rng.random_range(0..=2) {
|
||||
0 => AsteroidSize::Small,
|
||||
1 => AsteroidSize::Medium,
|
||||
2 => AsteroidSize::Large,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
events.write(SpawnAsteroid { pos, vel, size });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Lifetime(pub Timer);
|
||||
|
||||
pub fn tick_lifetimes(
|
||||
mut commands: Commands,
|
||||
time: Res<Time>,
|
||||
query: Query<(Entity, &mut Lifetime)>,
|
||||
) {
|
||||
for (e, mut life) in query {
|
||||
life.0.tick(time.delta());
|
||||
if life.0.just_finished() {
|
||||
commands.entity(e).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
194
src/objects.rs
Normal file
194
src/objects.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
//! This module contains all the "things" in the game.
|
||||
//!
|
||||
//! Asteroids, the player's ship, and such.
|
||||
|
||||
use bevy::{
|
||||
ecs::{
|
||||
component::Component,
|
||||
entity::Entity,
|
||||
event::{EventReader, EventWriter},
|
||||
query::With,
|
||||
system::{Commands, Query, Res, ResMut, Single},
|
||||
},
|
||||
math::{Vec2, Vec3, Vec3Swizzles},
|
||||
prelude::{Deref, DerefMut},
|
||||
render::mesh::Mesh2d,
|
||||
sprite::MeshMaterial2d,
|
||||
state::state::NextState,
|
||||
time::{Timer, TimerMode},
|
||||
transform::components::Transform,
|
||||
};
|
||||
use bevy_rapier2d::prelude::{ActiveCollisionTypes, ActiveEvents, Collider, Sensor};
|
||||
|
||||
use crate::{
|
||||
AngularVelocity, GameAssets, GameState, Lives,
|
||||
config::ASTEROID_LIFETIME,
|
||||
events::{AsteroidDestroy, BulletDestroy, ShipDestroy, SpawnAsteroid},
|
||||
machinery::Lifetime,
|
||||
physics::{Velocity, Wrapping},
|
||||
};
|
||||
|
||||
#[derive(Component, Deref, DerefMut)]
|
||||
pub struct Asteroid(pub AsteroidSize);
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum AsteroidSize {
|
||||
Small,
|
||||
Medium,
|
||||
Large,
|
||||
}
|
||||
|
||||
impl AsteroidSize {
|
||||
pub fn next(&self) -> Option<Self> {
|
||||
match self {
|
||||
AsteroidSize::Small => None,
|
||||
AsteroidSize::Medium => Some(AsteroidSize::Small),
|
||||
AsteroidSize::Large => Some(AsteroidSize::Medium),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Ship;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Bullet;
|
||||
|
||||
/// Responds to [`SpawnAsteroid`] events, spawning as specified
|
||||
pub fn spawn_asteroid(
|
||||
mut events: EventReader<SpawnAsteroid>,
|
||||
mut commands: Commands,
|
||||
game_assets: Res<GameAssets>,
|
||||
) {
|
||||
for spawn in events.read() {
|
||||
let (mesh, material) = match spawn.size {
|
||||
AsteroidSize::Small => game_assets.asteroid_small(),
|
||||
AsteroidSize::Medium => game_assets.asteroid_medium(),
|
||||
AsteroidSize::Large => game_assets.asteroid_large(),
|
||||
};
|
||||
|
||||
let collider_radius = match spawn.size {
|
||||
AsteroidSize::Small => 10.0,
|
||||
AsteroidSize::Medium => 20.0,
|
||||
AsteroidSize::Large => 40.0,
|
||||
};
|
||||
|
||||
commands.spawn((
|
||||
Asteroid(spawn.size),
|
||||
Collider::ball(collider_radius),
|
||||
Sensor,
|
||||
Transform::from_translation(spawn.pos.extend(0.0)),
|
||||
Velocity(spawn.vel),
|
||||
Mesh2d(mesh),
|
||||
MeshMaterial2d(material),
|
||||
Lifetime(Timer::from_seconds(ASTEROID_LIFETIME, TimerMode::Once)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Event listener for asteroid destruction events. Shrinks and multiplies
|
||||
/// asteroids until they vanish.
|
||||
///
|
||||
/// - Large -> 2x Medium
|
||||
/// - Medium -> 2x Small
|
||||
/// - Small -> (despawned)
|
||||
///
|
||||
/// The velocity of the child asteroids is scattered somewhat, as if they were
|
||||
/// explosively pushed apart.
|
||||
pub fn split_asteroids(
|
||||
mut destroy_events: EventReader<AsteroidDestroy>,
|
||||
mut respawn_events: EventWriter<SpawnAsteroid>,
|
||||
mut commands: Commands,
|
||||
query: Query<(&Transform, &Asteroid, &Velocity)>,
|
||||
) {
|
||||
for event in destroy_events.read() {
|
||||
if let Ok((transform, rock, velocity)) = query.get(event.0) {
|
||||
let next_size = rock.0.next();
|
||||
if let Some(size) = next_size {
|
||||
let pos = transform.translation.xy();
|
||||
let left_offset = Vec2::from_angle(0.4);
|
||||
let right_offset = Vec2::from_angle(-0.4);
|
||||
respawn_events.write(SpawnAsteroid {
|
||||
pos,
|
||||
vel: left_offset.rotate(velocity.0),
|
||||
size,
|
||||
});
|
||||
respawn_events.write(SpawnAsteroid {
|
||||
pos,
|
||||
vel: right_offset.rotate(velocity.0),
|
||||
size,
|
||||
});
|
||||
}
|
||||
// Always despawn the asteroid. New ones (may) be spawned in it's
|
||||
// place, but this one is gone.
|
||||
commands.entity(event.0).despawn();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn_player(mut commands: Commands, game_assets: Res<GameAssets>) {
|
||||
commands
|
||||
.spawn((
|
||||
Collider::ball(0.7),
|
||||
Sensor,
|
||||
ActiveEvents::COLLISION_EVENTS,
|
||||
ActiveCollisionTypes::STATIC_STATIC,
|
||||
Ship,
|
||||
Wrapping,
|
||||
Velocity(Vec2::ZERO),
|
||||
AngularVelocity(0.0),
|
||||
Mesh2d(game_assets.ship().0),
|
||||
MeshMaterial2d(game_assets.ship().1),
|
||||
Transform::default().with_scale(Vec3::new(20.0, 20.0, 20.0)),
|
||||
))
|
||||
.with_child((
|
||||
Mesh2d(game_assets.thruster_mesh()),
|
||||
MeshMaterial2d(game_assets.thruster_mat_inactive()),
|
||||
Transform::default()
|
||||
.with_scale(Vec3::splat(0.5))
|
||||
.with_translation(Vec3::new(-0.5, 0.0, -0.1)),
|
||||
));
|
||||
}
|
||||
|
||||
/// Watch for [`BulletDestroy`] events and despawn
|
||||
/// the associated bullet.
|
||||
pub fn bullet_impact_listener(mut commands: Commands, mut events: EventReader<BulletDestroy>) {
|
||||
for event in events.read() {
|
||||
commands.entity(event.0).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch for [`ShipDestroy`] events and update game state accordingly.
|
||||
///
|
||||
/// - Subtract a life
|
||||
/// - Check life count. If 0, go to game-over state
|
||||
/// - Clear all asteroids
|
||||
/// - Respawn player
|
||||
pub fn ship_impact_listener(
|
||||
mut events: EventReader<ShipDestroy>,
|
||||
mut commands: Commands,
|
||||
mut lives: ResMut<Lives>,
|
||||
rocks: Query<Entity, With<Asteroid>>,
|
||||
mut player: Single<(&mut Transform, &mut Velocity), With<Ship>>,
|
||||
mut next_state: ResMut<NextState<GameState>>,
|
||||
) {
|
||||
for _ in events.read() {
|
||||
// STEP 1: Decrement lives (and maybe go to game over)
|
||||
if lives.0 == 0 {
|
||||
// If already at 0, game is over.
|
||||
next_state.set(GameState::GameOver);
|
||||
} else {
|
||||
// Decrease life count.
|
||||
lives.0 -= 1;
|
||||
}
|
||||
|
||||
// STEP 2: Clear asteroids
|
||||
for rock in rocks {
|
||||
commands.entity(rock).despawn();
|
||||
}
|
||||
|
||||
// STEP 3: Respawn player (teleport them to the origin)
|
||||
player.0.translation = Vec3::ZERO;
|
||||
player.1.0 = Vec2::ZERO;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
//! Custom physics items
|
||||
//! TODO: Refactor in terms of Rapier2D, *or* implement colliders and remove it.
|
||||
|
||||
use crate::WorldSize;
|
||||
use crate::{
|
||||
WorldSize, events,
|
||||
objects::{Asteroid, Bullet, Ship},
|
||||
};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::pipeline::CollisionEvent;
|
||||
|
||||
#[derive(Clone, Component)]
|
||||
pub(crate) struct Velocity(pub(crate) bevy::math::Vec2);
|
||||
@@ -57,3 +61,66 @@ pub(crate) fn wrap_entities(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The collision event routing system.
|
||||
///
|
||||
/// When a `CollisionEvent` occurrs, this system checks which things collided
|
||||
/// and emits secondary events accordignly.
|
||||
///
|
||||
/// | Objects | Response |
|
||||
/// |-|-|
|
||||
/// | Ship & Asteroid | emits event [`ShipDestroy`](`crate::events::ShipDestroy`) |
|
||||
/// | Asteroid & Bullet | emits event [`AsteroidDestroy`](`crate::events::AsteroidDestroy`) |
|
||||
/// | Asteroid & Asteroid | Nothing. Asteroids won't collide with each other |
|
||||
/// | Bullet & Bullet | Nothing. Bullets won't collide with each other (and probably can't under normal gameplay conditions) |
|
||||
/// | Bullet & Ship | Nothing. The player shouldn't be able to shoot themselves (and the Flying Saucer hasn't been impl.'d, so it's bullets don't count) |
|
||||
pub fn collision_listener(
|
||||
mut collisions: EventReader<CollisionEvent>,
|
||||
mut ship_writer: EventWriter<events::ShipDestroy>,
|
||||
mut asteroid_writer: EventWriter<events::AsteroidDestroy>,
|
||||
mut bullet_writer: EventWriter<events::BulletDestroy>,
|
||||
player: Single<Entity, With<Ship>>,
|
||||
bullets: Query<&Bullet>,
|
||||
rocks: Query<&Asteroid>,
|
||||
) {
|
||||
for event in collisions.read() {
|
||||
if let CollisionEvent::Started(one, two, _flags) = event {
|
||||
// Valid collisions are:
|
||||
//
|
||||
// - Ship & Asteroid
|
||||
// - Bullet & Asteroid
|
||||
//
|
||||
// Asteroids don't collide with each other, bullets don't collide
|
||||
// with each other, and bullets don't collide with the player ship.
|
||||
|
||||
// Option 1: Ship & Asteroid
|
||||
if *one == *player {
|
||||
if rocks.contains(*two) {
|
||||
// player-asteroid collision
|
||||
dbg!("Writing ShipDestroy event");
|
||||
ship_writer.write(events::ShipDestroy);
|
||||
} // else, we don't care
|
||||
} else if *two == *player {
|
||||
if rocks.contains(*one) {
|
||||
dbg!("Writing ShipDestroy event");
|
||||
ship_writer.write(events::ShipDestroy);
|
||||
}
|
||||
}
|
||||
|
||||
// Option 2: Bullet & Asteroid
|
||||
if bullets.contains(*one) {
|
||||
if rocks.contains(*two) {
|
||||
dbg!("Writing AsteroidDestroy & BulletDestroy events");
|
||||
asteroid_writer.write(events::AsteroidDestroy(*two));
|
||||
bullet_writer.write(events::BulletDestroy(*one));
|
||||
}
|
||||
} else if rocks.contains(*one) {
|
||||
if bullets.contains(*two) {
|
||||
dbg!("Writing AsteroidDestroy & BulletDestroy events");
|
||||
asteroid_writer.write(events::AsteroidDestroy(*one));
|
||||
bullet_writer.write(events::BulletDestroy(*two));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
121
src/resources.rs
Normal file
121
src/resources.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
//! All the resources for the game
|
||||
|
||||
use bevy::{
|
||||
asset::{Assets, Handle},
|
||||
ecs::{
|
||||
resource::Resource,
|
||||
world::{FromWorld, World},
|
||||
},
|
||||
math::{
|
||||
Vec2,
|
||||
primitives::{Circle, Triangle2d},
|
||||
},
|
||||
prelude::{Deref, Reflect, ReflectResource},
|
||||
render::mesh::Mesh,
|
||||
sprite::ColorMaterial,
|
||||
};
|
||||
use bevy_inspector_egui::InspectorOptions;
|
||||
use bevy_inspector_egui::inspector_options::ReflectInspectorOptions;
|
||||
|
||||
use crate::{
|
||||
ASTEROID_SMALL_COLOR, BULLET_COLOR, PLAYER_SHIP_COLOR, SHIP_THRUSTER_COLOR_ACTIVE,
|
||||
SHIP_THRUSTER_COLOR_INACTIVE,
|
||||
};
|
||||
|
||||
#[derive(Resource, Debug, Deref, Clone, Copy)]
|
||||
pub struct Score(pub i32);
|
||||
|
||||
impl From<Score> for String {
|
||||
fn from(value: Score) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(InspectorOptions, Reflect, Resource, Debug, Deref, Clone, Copy)]
|
||||
#[reflect(Resource, InspectorOptions)]
|
||||
pub struct Lives(pub i32);
|
||||
|
||||
impl From<Lives> for String {
|
||||
fn from(value: Lives) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct WorldSize {
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
}
|
||||
|
||||
#[derive(Resource)]
|
||||
pub struct GameAssets {
|
||||
meshes: [Handle<Mesh>; 5],
|
||||
materials: [Handle<ColorMaterial>; 7],
|
||||
}
|
||||
|
||||
impl GameAssets {
|
||||
pub fn ship(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[0].clone(), self.materials[0].clone())
|
||||
}
|
||||
|
||||
// The thruster mesh is actually just the ship mesh
|
||||
pub fn thruster_mesh(&self) -> Handle<Mesh> {
|
||||
self.meshes[0].clone()
|
||||
}
|
||||
|
||||
// TODO: Look into parameterizing the material
|
||||
// A shader uniform should be able to do this, but I don't know how to
|
||||
// load those in Bevy.
|
||||
pub fn thruster_mat_inactive(&self) -> Handle<ColorMaterial> {
|
||||
self.materials[1].clone()
|
||||
}
|
||||
|
||||
pub fn thruster_mat_active(&self) -> Handle<ColorMaterial> {
|
||||
self.materials[2].clone()
|
||||
}
|
||||
|
||||
pub fn asteroid_small(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[1].clone(), self.materials[1].clone())
|
||||
}
|
||||
|
||||
pub fn asteroid_medium(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[2].clone(), self.materials[2].clone())
|
||||
}
|
||||
|
||||
pub fn asteroid_large(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[3].clone(), self.materials[3].clone())
|
||||
}
|
||||
|
||||
pub fn bullet(&self) -> (Handle<Mesh>, Handle<ColorMaterial>) {
|
||||
(self.meshes[4].clone(), self.materials[6].clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromWorld for GameAssets {
|
||||
fn from_world(world: &mut World) -> Self {
|
||||
let mut world_meshes = world.resource_mut::<Assets<Mesh>>();
|
||||
let meshes = [
|
||||
world_meshes.add(Triangle2d::new(
|
||||
Vec2::new(0.5, 0.0),
|
||||
Vec2::new(-0.5, 0.45),
|
||||
Vec2::new(-0.5, -0.45),
|
||||
)),
|
||||
world_meshes.add(Circle::new(10.0)),
|
||||
world_meshes.add(Circle::new(20.0)),
|
||||
world_meshes.add(Circle::new(40.0)),
|
||||
world_meshes.add(Circle::new(0.2)),
|
||||
];
|
||||
let mut world_materials = world.resource_mut::<Assets<ColorMaterial>>();
|
||||
let materials = [
|
||||
world_materials.add(PLAYER_SHIP_COLOR),
|
||||
world_materials.add(SHIP_THRUSTER_COLOR_INACTIVE),
|
||||
world_materials.add(SHIP_THRUSTER_COLOR_ACTIVE),
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
// TODO: asteroid medium and large colors
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
world_materials.add(ASTEROID_SMALL_COLOR),
|
||||
world_materials.add(BULLET_COLOR),
|
||||
];
|
||||
GameAssets { meshes, materials }
|
||||
}
|
||||
}
|
||||
82
src/ship.rs
82
src/ship.rs
@@ -1,82 +0,0 @@
|
||||
use crate::{
|
||||
AngularVelocity, GameAssets, GameState, Lives,
|
||||
asteroids::Asteroid,
|
||||
event::{BulletDestroy, ShipDestroy},
|
||||
physics::{Velocity, Wrapping},
|
||||
};
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::prelude::*;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Ship;
|
||||
|
||||
#[derive(Component)]
|
||||
pub struct Bullet;
|
||||
|
||||
pub fn spawn_player(mut commands: Commands, game_assets: Res<GameAssets>) {
|
||||
commands
|
||||
.spawn((
|
||||
Collider::ball(0.7),
|
||||
Sensor,
|
||||
ActiveEvents::COLLISION_EVENTS,
|
||||
ActiveCollisionTypes::STATIC_STATIC,
|
||||
Ship,
|
||||
Wrapping,
|
||||
Velocity(Vec2::ZERO),
|
||||
AngularVelocity(0.0),
|
||||
Mesh2d(game_assets.ship().0),
|
||||
MeshMaterial2d(game_assets.ship().1),
|
||||
Transform::default().with_scale(Vec3::new(20.0, 20.0, 20.0)),
|
||||
))
|
||||
.with_child((
|
||||
Mesh2d(game_assets.thruster_mesh()),
|
||||
MeshMaterial2d(game_assets.thruster_mat_inactive()),
|
||||
Transform::default()
|
||||
.with_scale(Vec3::splat(0.5))
|
||||
.with_translation(Vec3::new(-0.5, 0.0, -0.1)),
|
||||
));
|
||||
}
|
||||
|
||||
/// Watch for [`BulletDestroy`] events and despawn
|
||||
/// the associated bullet.
|
||||
pub fn bullet_impact_listener(mut commands: Commands, mut events: EventReader<BulletDestroy>) {
|
||||
for event in events.read() {
|
||||
commands.entity(event.0).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
/// Watch for [`ShipDestroy`] events and update game state accordingly.
|
||||
///
|
||||
/// - Subtract a life
|
||||
/// - Check life count. If 0, go to game-over state
|
||||
/// - Clear all asteroids
|
||||
/// - Respawn player
|
||||
pub fn ship_impact_listener(
|
||||
mut events: EventReader<ShipDestroy>,
|
||||
mut commands: Commands,
|
||||
mut lives: ResMut<Lives>,
|
||||
rocks: Query<Entity, With<Asteroid>>,
|
||||
mut player: Single<(&mut Transform, &mut Velocity), With<Ship>>,
|
||||
mut next_state: ResMut<NextState<GameState>>,
|
||||
) {
|
||||
for _ in events.read() {
|
||||
// STEP 1: Decrement lives (and maybe go to game over)
|
||||
if lives.0 == 0 {
|
||||
// If already at 0, game is over.
|
||||
next_state.set(GameState::GameOver);
|
||||
} else {
|
||||
// Decrease life count.
|
||||
lives.0 -= 1;
|
||||
}
|
||||
|
||||
// STEP 2: Clear asteroids
|
||||
for rock in rocks {
|
||||
commands.entity(rock).despawn();
|
||||
}
|
||||
|
||||
// STEP 3: Respawn player (teleport them to the origin)
|
||||
player.0.translation = Vec3::ZERO;
|
||||
player.1.0 = Vec2::ZERO;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
use crate::GameState;
|
||||
|
||||
use bevy::prelude::*;
|
||||
|
||||
pub struct GameMenuPlugin;
|
||||
|
||||
impl Plugin for GameMenuPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(GameState::TitleScreen), spawn_menu)
|
||||
.add_systems(OnExit(GameState::TitleScreen), despawn_menu)
|
||||
.add_systems(
|
||||
Update,
|
||||
handle_spacebar.run_if(in_state(GameState::TitleScreen)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Marker component for the title screen UI entity.
|
||||
// This way, a query for the TitleUI can be used to despawn the title screen
|
||||
#[derive(Component)]
|
||||
struct TitleUI;
|
||||
|
||||
fn spawn_menu(mut commands: Commands) {
|
||||
commands
|
||||
.spawn((
|
||||
TitleUI,
|
||||
Node {
|
||||
flex_direction: FlexDirection::Column,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.with_children(|cmds| {
|
||||
cmds.spawn((
|
||||
Text::new("Robert's Bad Asteroids Game"),
|
||||
TextFont::from_font_size(50.0),
|
||||
));
|
||||
cmds.spawn((
|
||||
Text::new("Press space to begin"),
|
||||
TextFont::from_font_size(40.0),
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
fn despawn_menu(mut commands: Commands, to_despawn: Query<Entity, With<TitleUI>>) {
|
||||
for entity in &to_despawn {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_spacebar(input: Res<ButtonInput<KeyCode>>, mut game_state: ResMut<NextState<GameState>>) {
|
||||
if input.just_pressed(KeyCode::Space) {
|
||||
game_state.set(GameState::GetReady);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
use crate::GameState;
|
||||
use crate::{
|
||||
GameState,
|
||||
resources::{Lives, Score},
|
||||
};
|
||||
|
||||
use bevy::{
|
||||
color::palettes::css::{BLACK, GREEN, LIGHT_BLUE, RED},
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
pub fn spawn_ui(mut commands: Commands, score: Res<Score>, lives: Res<Lives>) {
|
||||
commands.spawn((
|
||||
Text::new(format!("Score: {score:?} | Lives: {lives:?}")),
|
||||
TextFont::from_font_size(25.0),
|
||||
));
|
||||
}
|
||||
|
||||
pub fn preparation_widget_plugin(app: &mut App) {
|
||||
app.add_systems(OnEnter(GameState::GetReady), spawn_get_ready)
|
||||
.add_systems(OnExit(GameState::GetReady), despawn_get_ready)
|
||||
@@ -97,3 +107,54 @@ fn animate_get_ready_widget(
|
||||
game_state.set(GameState::Playing);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GameMenuPlugin;
|
||||
|
||||
impl Plugin for GameMenuPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
app.add_systems(OnEnter(GameState::TitleScreen), spawn_menu)
|
||||
.add_systems(OnExit(GameState::TitleScreen), despawn_menu)
|
||||
.add_systems(
|
||||
Update,
|
||||
handle_spacebar.run_if(in_state(GameState::TitleScreen)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Marker component for the title screen UI entity.
|
||||
// This way, a query for the TitleUI can be used to despawn the title screen
|
||||
#[derive(Component)]
|
||||
struct TitleUI;
|
||||
|
||||
fn spawn_menu(mut commands: Commands) {
|
||||
commands
|
||||
.spawn((
|
||||
TitleUI,
|
||||
Node {
|
||||
flex_direction: FlexDirection::Column,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
.with_children(|cmds| {
|
||||
cmds.spawn((
|
||||
Text::new("Robert's Bad Asteroids Game"),
|
||||
TextFont::from_font_size(50.0),
|
||||
));
|
||||
cmds.spawn((
|
||||
Text::new("Press space to begin"),
|
||||
TextFont::from_font_size(40.0),
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
fn despawn_menu(mut commands: Commands, to_despawn: Query<Entity, With<TitleUI>>) {
|
||||
for entity in &to_despawn {
|
||||
commands.entity(entity).despawn();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_spacebar(input: Res<ButtonInput<KeyCode>>, mut game_state: ResMut<NextState<GameState>>) {
|
||||
if input.just_pressed(KeyCode::Space) {
|
||||
game_state.set(GameState::GetReady);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user