]> git.taranathan.com Git - asteroids.git/commitdiff
working
authormoo <moogoesmeow123@gmail.com>
Tue, 17 Mar 2026 21:56:49 +0000 (14:56 -0700)
committermoo <moogoesmeow123@gmail.com>
Tue, 17 Mar 2026 21:56:49 +0000 (14:56 -0700)
src/entities.rs
src/main.rs
src/systems.rs

index 13687f1bd92446dc5774dd65cd46bb122aedb92c..1bc88dbd2173784bcc6f4560b5b08da6a6e27d82 100644 (file)
@@ -2,7 +2,7 @@ use bevy::prelude::*;
 
 //=================== Resources ===================
 
-#[derive(Resource, Default)]
+#[derive(Resource)]
 pub struct Sprites {
     pub ship_sprite: Handle<Image>,
     pub asteroid_sprite: Handle<Image>,
@@ -36,4 +36,4 @@ pub struct Velocity {
     pub linear: Vec2,
     ///degs per sec, positive is clockwise
     pub angular: f32,
-}
\ No newline at end of file
+}
index bba292748c128120de0a8f809457a0bbe30ffae5..4729732f7cd6545b2262afe5cf8d367d23dc6559 100644 (file)
@@ -1,63 +1,9 @@
-use bevy::{
-    color::palettes::css::{GREEN, RED},
-    gizmos::circles,
-    prelude::*,
-    sprite, transform,
-    window::WindowResolution,
-};
-use rand::Rng;
-use std::f32::consts::PI;
+mod entities;
+mod systems;
 
-const PLAYER_SIZE: f32 = 30.0;
-const PLAYER_ROTATION_SPEED: f32 = 3.0 * PI / 180.0;
-const PLAYER_ACCELERATION: f32 = 0.5;
-const PLAYER_FRICTION: f32 = 0.99;
-const PLAYER_MAX_SPEED: f32 = 5.0;
-const PLAYER_Z: f32 = 3.0;
-
-const BULLET_SIZE: f32 = 5.0;
-const BULLET_SPEED: f32 = 10.0;
-const BULLET_LIFETIME: f32 = 1.0; // seconds
-const BULLET_Z: f32 = 2.0;
-
-const ASTEROID_SIZE: f32 = 150.0;
-const ASTEROID_SPEED: f32 = 2.0;
-const INITIAL_ASTEROID_COUNT: i32 = 5;
-const ASTEROID_Z: f32 = 1.0;
-
-#[derive(Resource)]
-struct Sprites {
-    ship_sprite: Handle<Image>,
-    asteroid_sprite: Handle<Image>,
-}
-
-#[derive(Component)]
-struct Player {
-    lives: i8,
-}
-
-#[derive(Component)]
-struct Asteroid;
-
-#[derive(Component)]
-struct Collider {
-    radius: f32,
-}
-
-#[derive(Component)]
-struct Bullet {
-    lifetime: Timer,
-}
-
-#[derive(Component)]
-struct Velocity {
-    linear: Vec2,
-    ///degs per sec, positive is clockwise
-    angular: f32,
-}
-
-#[derive(Resource, Deref, DerefMut)]
-struct WindowSize(Vec2);
+use bevy::{prelude::*, window::WindowResolution};
+use entities::*;
+use systems::*;
 
 fn main() {
     App::new()
@@ -75,7 +21,7 @@ fn main() {
             asteroid_sprite: Handle::default(),
         })
         .add_systems(Startup, (load_sprites, setup).chain())
-        .add_systems(Update, (resolution))
+        .add_systems(Update, resolution)
         .add_systems(
             Update,
             (
@@ -85,237 +31,9 @@ fn main() {
                 bullet_lifetime_system,
                 screen_wrap_system,
                 collision_system,
+                restart_system,
             )
                 .chain(),
         )
         .run();
 }
-
-fn load_sprites(
-    mut commands: Commands,
-    asset_server: Res<AssetServer>,
-    mut sprites: ResMut<Sprites>,
-) {
-    sprites.ship_sprite = asset_server.load("ship.png");
-    sprites.asteroid_sprite = asset_server.load("asteroid.png");
-}
-
-fn setup(mut commands: Commands, window_size: Res<WindowSize>, sprites: Res<Sprites>) {
-    commands.spawn(Camera2d::default());
-    commands.spawn((
-        Sprite::from_image(sprites.ship_sprite.clone()),
-        Transform {
-            scale: Vec3::splat(0.2),
-            translation: Vec3::new(0.0, 0.0, PLAYER_Z),
-            ..default()
-        },
-        Player { lives: 3 },
-        Velocity {
-            linear: Vec2::ZERO,
-            angular: 0.0,
-        },
-        Collider {
-            radius: PLAYER_SIZE / 2.0,
-        },
-    ));
-
-    let mut rng = rand::rng();
-    for _ in 0..INITIAL_ASTEROID_COUNT {
-        let x = rng.random_range(-(window_size.0.x) / 2.0..window_size.0.x as f32 / 2.0);
-        let y = rng.random_range(-(window_size.0.y as f32) / 2.0..window_size.0.y as f32 / 2.0);
-        let angle = rng.random_range(0.0..2.0 * PI);
-
-        commands.spawn((
-            Transform {
-                translation: Vec3::new(x, y, ASTEROID_Z),
-                scale: Vec3::splat(0.5),
-                rotation: Quat::from_rotation_z(rng.random_range(0.0..2.0 * PI)),
-                ..default()
-            },
-            Sprite::from_image(sprites.asteroid_sprite.clone()),
-            Asteroid,
-            Velocity {
-                linear: Vec2::new(angle.cos(), angle.sin()) * ASTEROID_SPEED,
-                angular: rng.random_range(-0.5..0.5),
-            },
-            Collider {
-                radius: ASTEROID_SIZE / 2.0,
-            },
-        ));
-    }
-}
-
-fn player_movement_system(
-    keyboard_input: Res<ButtonInput<KeyCode>>,
-    mut player: Query<(&mut Transform, &mut Velocity), With<Player>>,
-    mut commands: Commands,
-) {
-    if keyboard_input.pressed(KeyCode::KeyQ) {
-        commands.write_message(AppExit::Success);
-    }
-
-    if let Ok((mut transform, mut velocity)) = player.single_mut() {
-        if keyboard_input.pressed(KeyCode::ArrowLeft) {
-            transform.rotate_z(PLAYER_ROTATION_SPEED);
-            // velocity.angular += PLAYER_ROTATION_SPEED;
-        }
-        if keyboard_input.pressed(KeyCode::ArrowRight) {
-            transform.rotate_z(-PLAYER_ROTATION_SPEED);
-            // velocity.angular -= PLAYER_ROTATION_SPEED;
-        }
-
-        if keyboard_input.pressed(KeyCode::ArrowUp) {
-            let direction = transform.rotation * Vec3::Y;
-            velocity.linear += direction.truncate() * PLAYER_ACCELERATION;
-
-            // max spped
-            // if velocity.linear.length() > PLAYER_MAX_SPEED {
-            //     velocity.linear = velocity.linear.normalize() * PLAYER_MAX_SPEED;
-            // }
-        }
-
-        velocity.linear *= PLAYER_FRICTION;
-    }
-}
-
-fn player_shooting_system(
-    mut commands: Commands,
-    keyboard_input: Res<ButtonInput<KeyCode>>,
-    query: Query<&Transform, With<Player>>,
-) {
-    if keyboard_input.just_pressed(KeyCode::Space) {
-        if let Ok(player_transform) = query.single() {
-            let direction = player_transform.rotation * Vec3::Y;
-            let bullet_velocity = direction.truncate() * BULLET_SPEED;
-
-            commands.spawn((
-                Sprite::from_color(Color::WHITE, Vec2::splat(BULLET_SIZE)),
-                Transform {
-                    translation: Vec3 {
-                        x: player_transform.translation.x,
-                        y: player_transform.translation.y,
-                        z: BULLET_Z,
-                    },
-                    ..default()
-                },
-                Bullet {
-                    lifetime: Timer::from_seconds(BULLET_LIFETIME, TimerMode::Once),
-                },
-                Velocity {
-                    linear: bullet_velocity,
-                    angular: 0.0,
-                },
-                Collider {
-                    radius: BULLET_SIZE / 2.0,
-                },
-            ));
-        }
-    }
-}
-
-fn move_system(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
-    for (mut transform, velocity) in &mut query {
-        // transform.rotate_z(velocity.angular * time.delta_secs());
-        transform.translation.x += velocity.linear.x * time.delta_secs() * 100.0;
-        transform.translation.y += velocity.linear.y * time.delta_secs() * 100.0;
-    }
-}
-
-fn bullet_lifetime_system(
-    mut commands: Commands,
-    time: Res<Time>,
-    mut query: Query<(Entity, &mut Bullet)>,
-) {
-    for (entity, mut bullet) in &mut query {
-        bullet.lifetime.tick(time.delta());
-        if bullet.lifetime.is_finished() {
-            commands.entity(entity).despawn();
-        }
-    }
-}
-
-fn resolution(window: Single<&Window>, mut window_size: ResMut<WindowSize>) {
-    window_size.0 = window.size();
-}
-
-fn screen_wrap_system(mut query: Query<&mut Transform>, window_size: Res<WindowSize>) {
-    let half_width = window_size.0.x as f32 / 2.0;
-    let half_height = window_size.0.y as f32 / 2.0;
-
-    for mut transform in &mut query {
-        if transform.translation.x > half_width {
-            transform.translation.x = -half_width;
-        }
-        if transform.translation.x < -half_width {
-            transform.translation.x = half_width;
-        }
-        if transform.translation.y > half_height {
-            transform.translation.y = -half_height;
-        }
-        if transform.translation.y < -half_height {
-            transform.translation.y = half_height;
-        }
-    }
-}
-
-fn collision_system(
-    mut commands: Commands,
-    mut player_query: Query<(Entity, &Transform, &Collider, &mut Player)>,
-    asteroid_query: Query<(Entity, &Transform, &Collider), With<Asteroid>>,
-    bullet_query: Query<(Entity, &Transform, &Collider), With<Bullet>>,
-    mut gizmos: Gizmos,
-) {
-    if let Ok((player_entity, player_transform, player_collider, mut player)) =
-        player_query.single_mut()
-    {
-        gizmos
-            .circle_2d(
-                Isometry2d::new(player_transform.translation.truncate(), 0.0.into()),
-                player_collider.radius,
-                RED,
-            )
-            .resolution(64);
-
-        for (asteroid_entity, asteroid_transform, asteroid_collider) in &asteroid_query {
-            gizmos
-                .circle_2d(
-                    Isometry2d::new(asteroid_transform.translation.truncate(), 0.0.into()),
-                    asteroid_collider.radius,
-                    GREEN,
-                )
-                .resolution(64);
-            let distance = player_transform
-                .translation
-                .truncate()
-                .distance(asteroid_transform.translation.truncate());
-            if distance < player_collider.radius + asteroid_collider.radius {
-                commands.entity(asteroid_entity).despawn();
-
-                player.lives -= 1;
-                println!("Player hit an asteroid!");
-                if player.lives <= 0 {
-                    commands.entity(player_entity).despawn();
-                    println!("Game Over!");
-                }
-                // To avoid panic on next collision check in the same frame
-                break;
-            }
-        }
-    }
-
-    for (bullet_entity, bullet_transform, bullet_collider) in &bullet_query {
-        for (asteroid_entity, asteroid_transform, asteroid_collider) in &asteroid_query {
-            let distance = bullet_transform
-                .translation
-                .truncate()
-                .distance(asteroid_transform.translation.truncate());
-
-            if distance < bullet_collider.radius + asteroid_collider.radius {
-                commands.entity(bullet_entity).despawn();
-                commands.entity(asteroid_entity).despawn();
-                //todo spawn smaller asteroids
-                break;
-            }
-        }
-    }
-}
index 3d7223c10b9cbd74277be32d74893411e7deb531..ada3820b73060b0ecefff2b66024ff45000ee5c8 100644 (file)
@@ -1,7 +1,7 @@
 use bevy::{
     app::AppExit,
     color::palettes::css::{GREEN, RED},
-    gizmos::circles,
+    ecs::system::IntoResult,
     prelude::*,
 };
 use rand::Rng;
@@ -9,40 +9,38 @@ use std::f32::consts::PI;
 
 use crate::entities::*;
 
-pub const PLAYER_SIZE: f32 = 30.0;
+const PLAYER_SIZE: f32 = 30.0;
 const PLAYER_ROTATION_SPEED: f32 = 3.0 * PI / 180.0;
 const PLAYER_ACCELERATION: f32 = 0.5;
 const PLAYER_FRICTION: f32 = 0.99;
-// const PLAYER_MAX_SPEED: f32 = 5.0;
-pub const PLAYER_Z: f32 = 3.0;
+const PLAYER_Z: f32 = 3.0;
 
-pub const BULLET_SIZE: f32 = 5.0;
+const BULLET_SIZE: f32 = 5.0;
 const BULLET_SPEED: f32 = 10.0;
-const BULLET_LIFETIME: f32 = 1.0; // seconds
-pub const BULLET_Z: f32 = 2.0;
+const BULLET_LIFETIME: f32 = 1.0;
+const BULLET_Z: f32 = 2.0;
 
-pub const ASTEROID_SIZE: f32 = 150.0;
+const ASTEROID_SIZE: f32 = 150.0;
 const ASTEROID_SPEED: f32 = 2.0;
 const INITIAL_ASTEROID_COUNT: i32 = 5;
-pub const ASTEROID_Z: f32 = 1.0;
+const ASTEROID_Z: f32 = 1.0;
 
-pub fn load_sprites(mut commands: Commands, asset_server: Res<AssetServer>) {
-    commands.insert_resource(Sprites {
-        ship_sprite: asset_server.load("ship.png"),
-        asteroid_sprite: asset_server.load("asteroid.png"),
-    });
+pub fn load_sprites(
+    mut commands: Commands,
+    asset_server: Res<AssetServer>,
+    mut sprites: ResMut<Sprites>,
+) {
+    sprites.ship_sprite = asset_server.load("ship.png");
+    sprites.asteroid_sprite = asset_server.load("asteroid.png");
 }
 
 pub fn setup(mut commands: Commands, window_size: Res<WindowSize>, sprites: Res<Sprites>) {
     commands.spawn(Camera2d::default());
     commands.spawn((
-        SpriteBundle {
-            texture: sprites.ship_sprite.clone(),
-            transform: Transform {
-                scale: Vec3::splat(0.2),
-                translation: Vec3::new(0.0, 0.0, PLAYER_Z),
-                ..default()
-            },
+        Sprite::from_image(sprites.ship_sprite.clone()),
+        Transform {
+            scale: Vec3::splat(0.2),
+            translation: Vec3::new(0.0, 0.0, PLAYER_Z),
             ..default()
         },
         Player { lives: 3 },
@@ -55,27 +53,24 @@ pub fn setup(mut commands: Commands, window_size: Res<WindowSize>, sprites: Res<
         },
     ));
 
-    let mut rng = rand::thread_rng();
+    let mut rng = rand::rng();
     for _ in 0..INITIAL_ASTEROID_COUNT {
-        let x = rng.gen_range(-(window_size.0.x) / 2.0..window_size.0.x / 2.0);
-        let y = rng.gen_range(-(window_size.0.y) / 2.0..window_size.0.y / 2.0);
-        let angle = rng.gen_range(0.0..2.0 * PI);
+        let x = rng.random_range(-(window_size.0.x) / 2.0..window_size.0.x / 2.0);
+        let y = rng.random_range(-(window_size.0.y) / 2.0..window_size.0.y / 2.0);
+        let angle = rng.random_range(0.0..2.0 * PI);
 
         commands.spawn((
-            SpriteBundle {
-                texture: sprites.asteroid_sprite.clone(),
-                transform: Transform {
-                    translation: Vec3::new(x, y, ASTEROID_Z),
-                    scale: Vec3::splat(0.5),
-                    rotation: Quat::from_rotation_z(rng.gen_range(0.0..2.0 * PI)),
-                    ..default()
-                },
+            Transform {
+                translation: Vec3::new(x, y, ASTEROID_Z),
+                scale: Vec3::splat(0.5),
+                rotation: Quat::from_rotation_z(rng.random_range(0.0..2.0 * PI)),
                 ..default()
             },
+            Sprite::from_image(sprites.asteroid_sprite.clone()),
             Asteroid,
             Velocity {
                 linear: Vec2::new(angle.cos(), angle.sin()) * ASTEROID_SPEED,
-                angular: rng.gen_range(-0.5..0.5),
+                angular: rng.random_range(-0.5..0.5),
             },
             Collider {
                 radius: ASTEROID_SIZE / 2.0,
@@ -85,12 +80,12 @@ pub fn setup(mut commands: Commands, window_size: Res<WindowSize>, sprites: Res<
 }
 
 pub fn player_movement_system(
-    mut commands: Commands,
     keyboard_input: Res<ButtonInput<KeyCode>>,
     mut player: Query<(&mut Transform, &mut Velocity), With<Player>>,
+    mut commands: Commands,
 ) {
     if keyboard_input.pressed(KeyCode::KeyQ) {
-        commands.add(AppExit);
+        commands.write_message(AppExit::Success);
     }
 
     if let Ok((mut transform, mut velocity)) = player.single_mut() {
@@ -121,19 +116,12 @@ pub fn player_shooting_system(
             let bullet_velocity = direction.truncate() * BULLET_SPEED;
 
             commands.spawn((
-                SpriteBundle {
-                    sprite: Sprite {
-                        color: Color::WHITE,
-                        custom_size: Some(Vec2::splat(BULLET_SIZE)),
-                        ..default()
-                    },
-                    transform: Transform {
-                        translation: Vec3::new(
-                            player_transform.translation.x,
-                            player_transform.translation.y,
-                            BULLET_Z,
-                        ),
-                        ..default()
+                Sprite::from_color(Color::WHITE, Vec2::splat(BULLET_SIZE)),
+                Transform {
+                    translation: Vec3 {
+                        x: player_transform.translation.x,
+                        y: player_transform.translation.y,
+                        z: BULLET_Z,
                     },
                     ..default()
                 },
@@ -154,8 +142,8 @@ pub fn player_shooting_system(
 
 pub fn move_system(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
     for (mut transform, velocity) in &mut query {
-        transform.translation.x += velocity.linear.x * time.delta_seconds() * 100.0;
-        transform.translation.y += velocity.linear.y * time.delta_seconds() * 100.0;
+        transform.translation.x += velocity.linear.x * time.delta_secs() * 100.0;
+        transform.translation.y += velocity.linear.y * time.delta_secs() * 100.0;
     }
 }
 
@@ -166,21 +154,19 @@ pub fn bullet_lifetime_system(
 ) {
     for (entity, mut bullet) in &mut query {
         bullet.lifetime.tick(time.delta());
-        if bullet.lifetime.finished() {
+        if bullet.lifetime.is_finished() {
             commands.entity(entity).despawn();
         }
     }
 }
 
-pub fn resolution(mut windows: Query<&mut Window>, mut window_size: ResMut<WindowSize>) {
-    if let Some(window) = windows.iter_mut().next() {
-        window_size.0 = Vec2::new(window.width(), window.height());
-    }
+pub fn resolution(window: Single<&Window>, mut window_size: ResMut<WindowSize>) {
+    window_size.0 = window.size();
 }
 
 pub fn screen_wrap_system(mut query: Query<&mut Transform>, window_size: Res<WindowSize>) {
-    let half_width = window_size.0.x / 2.0;
-    let half_height = window_size.0.y / 2.0;
+    let half_width = window_size.0.x as f32 / 2.0;
+    let half_height = window_size.0.y as f32 / 2.0;
 
     for mut transform in &mut query {
         if transform.translation.x > half_width {
@@ -198,6 +184,28 @@ pub fn screen_wrap_system(mut query: Query<&mut Transform>, window_size: Res<Win
     }
 }
 
+pub fn restart_system(
+    mut commands: Commands,
+    keyboard_input: Res<ButtonInput<KeyCode>>,
+    player_query: Query<Entity, With<Player>>,
+    camera_query: Query<Entity, With<Camera2d>>,
+    asteroid_query: Query<Entity, With<Asteroid>>,
+) {
+    if keyboard_input.just_pressed(KeyCode::KeyR) {
+        cleanup(&mut commands, player_query);
+        cleanup(&mut commands, camera_query);
+        cleanup(&mut commands, asteroid_query);
+
+        commands.run_schedule(Startup);
+    }
+}
+
+fn cleanup<T: Component>(commands: &mut Commands, query: Query<Entity, With<T>>) {
+    for e in &query {
+        commands.entity(e).despawn();
+    }
+}
+
 pub fn collision_system(
     mut commands: Commands,
     mut player_query: Query<(Entity, &Transform, &Collider, &mut Player)>,
@@ -208,21 +216,26 @@ pub fn collision_system(
     if let Ok((player_entity, player_transform, player_collider, mut player)) =
         player_query.single_mut()
     {
-        gizmos.circle_2d(
-            player_transform.translation.truncate(),
-            player_collider.radius,
-            RED,
-        );
+        gizmos
+            .circle_2d(
+                Isometry2d::new(player_transform.translation.truncate(), 0.0.into()),
+                player_collider.radius,
+                RED,
+            )
+            .resolution(64);
 
         for (asteroid_entity, asteroid_transform, asteroid_collider) in &asteroid_query {
-            gizmos.circle_2d(
-                asteroid_transform.translation.truncate(),
-                asteroid_collider.radius,
-                GREEN,
-            );
+            gizmos
+                .circle_2d(
+                    Isometry2d::new(asteroid_transform.translation.truncate(), 0.0.into()),
+                    asteroid_collider.radius,
+                    GREEN,
+                )
+                .resolution(64);
             let distance = player_transform
                 .translation
-                .distance(asteroid_transform.translation);
+                .truncate()
+                .distance(asteroid_transform.translation.truncate());
             if distance < player_collider.radius + asteroid_collider.radius {
                 commands.entity(asteroid_entity).despawn();
 
@@ -241,7 +254,8 @@ pub fn collision_system(
         for (asteroid_entity, asteroid_transform, asteroid_collider) in &asteroid_query {
             let distance = bullet_transform
                 .translation
-                .distance(asteroid_transform.translation);
+                .truncate()
+                .distance(asteroid_transform.translation.truncate());
 
             if distance < bullet_collider.radius + asteroid_collider.radius {
                 commands.entity(bullet_entity).despawn();
@@ -250,4 +264,4 @@ pub fn collision_system(
             }
         }
     }
-}
\ No newline at end of file
+}