主頁 > 後端開發 > 一個簡單的 rust 專案 飛機大戰

一個簡單的 rust 專案 飛機大戰

2023-04-20 07:21:39 後端開發

Rust 實作的飛機游戲

簡介

一個使用 bevy 引擎制作的飛機游戲,

原視頻教程地址,github 地址,

因為 bevy 已經升級到 0.10.1 了,所以重新做一遍,順帶手出個教程,

下面是做的部分變動:

  • 將激光以及玩家的移動模塊進行了拆分,
  • 新增了背景圖片,
  • 新增了游戲狀態管理 Welcome/InGame/Paused,
  • 新增了聲音播放模塊,
  • 新增了游戲記分板,

通過左右方向鍵進行控制,使用空格發射激光,
按 P 暫停游戲,按 S 恢復游戲,
更新后的GitHub地址

代碼結構

·
├── assets/
│   ├──audios/
│   ├──fonts/
│   └──images/
├── src/
│   ├──enemy/
│   │  ├── formation.rs
│   │  └── mod.rs
│   ├── components.rs
│   ├── constants.rs
│   ├── main.rs
│   ├── player.rs
│   ├── resource.rs
│   └── state.rs
├── Cargo.lock
└── Cargo.toml
  • assets/audios 聲音資源檔案,
  • assets/fonts 字體資源檔案,
  • assets/images 圖片資源檔案,
  • enemy/formation.rs 敵人陣型系統的實作,
  • enemy/mod.rs 敵人插件,生成、移動、攻擊的實作,
  • components.rs 負責游戲的邏輯、控制、等內容,
  • constants.rs 負責存盤游戲中用到的常量,
  • main.rs 負責游戲的邏輯、控制、等內容,
  • player.rs 玩家角色插件,生成、移動、攻擊、鍵盤處理的實作,
  • resource.rs 游戲資源定義,
  • state.rs 游戲組件定義,

兩點間的距離公式 \(|AB|=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}\)

enemy/formation.rs

use bevy::prelude::{Component, Resource};
use rand::{thread_rng, Rng};

use crate::{WinSize, BASE_SPEED, FORMATION_MEMBER_MAX};

/// 敵人陣型
#[derive(Component, Clone)]
pub struct Formation {
    /// 啟始位置
    pub start: (f32, f32),
    /// 半徑
    pub radius: (f32, f32),
    /// 原點
    pub pivot: (f32, f32),
    /// 速度
    pub speed: f32,
    /// 角度
    pub angle: f32,
}

/// 陣型資源
#[derive(Resource, Default)]
pub struct FormationMaker {
    /// 當前陣型
    current_template: Option<Formation>,
    /// 當前數量
    current_members: u32,
}

impl FormationMaker {
    pub fn make(&mut self, win_size: &WinSize) -> Formation {
        match (
            &self.current_template,
            self.current_members >= FORMATION_MEMBER_MAX,
        ) {
            // 當前陣型還有空位 直接加入
            (Some(template), false) => {
                self.current_members += 1;
                template.clone()
            }
            // 當前陣型沒有空位,或還沒有陣型,需要創建新的陣型
            _ => {
                let mut rng = thread_rng();

                // 生成 起點坐標
                let w_spawn = win_size.w / 2. + 100.;
                let h_spawn = win_size.h / 2. + 100.;
                let x = if rng.gen_bool(0.5) { w_spawn } else { -w_spawn };
                let y = rng.gen_range(-h_spawn..h_spawn);
                let start = (x, y);

                // 生成原點坐標
                let w_spawn = win_size.w / 4.;
                let h_spawn = win_size.h / 3. + 50.;
                let pivot = (
                    rng.gen_range(-w_spawn..w_spawn),
                    rng.gen_range(0. ..h_spawn),
                );

                // 生成半徑
                let radius = (rng.gen_range(80. ..150.), 100.);

                // 計算初始角度
                let angle = (y - pivot.1).atan2(x - pivot.0);

                // 速度
                let speed = BASE_SPEED;

                let formation = Formation {
                    start,
                    pivot,
                    radius,
                    angle,
                    speed,
                };

                self.current_template = Some(formation.clone());
                self.current_members = 1;
                formation
            }
        }
    }
}

enemy/mod.rs

use std::{f32::consts::PI, time::Duration};

use crate::{
    components::{Enemy, FromEnemy, Laser, Movable, SpriteSize, Velocity},
    resource::GameState,
    GameTextures, MaxEnemy, WinSize, ENEMY_LASER_SIZE, ENEMY_SIZE, MAX_ENEMY, SPRITE_SCALE,
    TIME_STEP,
};

use bevy::{prelude::*, time::common_conditions::on_timer};
use rand::{thread_rng, Rng};

use self::formation::{Formation, FormationMaker};

mod formation;

#[derive(Component)]
pub struct EnemyPlugin;

impl Plugin for EnemyPlugin {
    fn build(&self, app: &mut App) {
        // 間隔執行
        app.insert_resource(FormationMaker::default())
            .add_system(
                enemy_spawn_system
                    .run_if(on_timer(Duration::from_secs_f32(0.5)))
                    .in_set(OnUpdate(GameState::InGame)),
            )
            .add_system(
                enemy_fire_system
                    .run_if(enemy_fire_criteria)
                    .in_set(OnUpdate(GameState::InGame)),
            )
            .add_system(enemy_movement_system.in_set(OnUpdate(GameState::InGame)));
    }
}

/// 敵人生成系統
fn enemy_spawn_system(
    mut commands: Commands,
    mut max_enemy: ResMut<MaxEnemy>,
    mut formation_maker: ResMut<FormationMaker>,
    game_textures: Res<GameTextures>,
    win_size: Res<WinSize>,
) {
    // 如果當前的敵人數量大于等于最大敵人數量,則不再產生新的敵人
    if max_enemy.0 >= MAX_ENEMY {
        return;
    }

    // 隨機生成
    // let mut rng = thread_rng();
    // let w_span = win_size.w / 2. - 100.;
    // let h_span = win_size.h / 2. - 100.;
    // let x = rng.gen_range(-w_span..w_span);
    // let y = rng.gen_range(-h_span..h_span);

    // 使用 陣型
    let formation = formation_maker.make(&win_size);
    let (x, y) = formation.start;

    commands
        .spawn(SpriteBundle {
            texture: game_textures.enemy.clone(),
            transform: Transform {
                // 坐標
                translation: Vec3::new(x, y, 10.),
                // 縮放
                scale: Vec3::new(SPRITE_SCALE, SPRITE_SCALE, 1.),
                // 旋轉
                rotation: Quat::IDENTITY,
            },
            ..Default::default()
        })
        .insert(Enemy)
        .insert(formation)
        .insert(SpriteSize::from(ENEMY_SIZE));
    max_enemy.0 += 1;
}

/// 敵人射擊系統
fn enemy_fire_system(
    mut commands: Commands,
    game_textures: Res<GameTextures>,
    query: Query<&Transform, With<Enemy>>,
) {
    for &enemy_tf in query.iter() {
        let (x, y) = (enemy_tf.translation.x, enemy_tf.translation.y);

        commands
            .spawn(SpriteBundle {
                texture: game_textures.enemy_laser.clone(),
                transform: Transform {
                    translation: Vec3::new(x, y, 1.),
                    scale: Vec3::new(SPRITE_SCALE, SPRITE_SCALE, 1.),
                    rotation: Quat::from_rotation_x(PI),
                },
                ..Default::default()
            })
            .insert(Laser)
            .insert(SpriteSize::from(ENEMY_LASER_SIZE))
            .insert(FromEnemy)
            .insert(Movable { auto_despawn: true })
            .insert(Velocity::new(0., -1.));
    }
}

/// 是否發射攻擊
fn enemy_fire_criteria() -> bool {
    if thread_rng().gen_bool(1. / 60.) {
        true
    } else {
        false
    }
}

/// 敵人移動系統
///
/// 兩點間的距離公式 $|AB|=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$
fn enemy_movement_system(mut query: Query<(&mut Transform, &mut Formation), With<Enemy>>) {
    // 當前時間
    // let now = time.elapsed_seconds();
    for (mut transform, mut formation) in query.iter_mut() {
        // 當前坐標
        let (x_org, y_org) = (transform.translation.x, transform.translation.y);
        // let (x_org, y_org) = formation.start;

        // 單位時間內最大移動距離
        // let max_distance = BASE_SPEED * TIME_STEP;
        let max_distance = formation.speed * TIME_STEP;

        // 方向 1 順時針 -1 逆時針
        // let dir = -1.;
        let dir = if formation.start.0 < 0. { 1. } else { -1. };
        // 中心點
        // let (x_pivot, y_pivot) = (0., 0.);
        let (x_pivot, y_pivot) = formation.pivot;
        // 半徑
        // let (x_radius, y_radius) = (200., 130.);
        let (x_radius, y_radius) = formation.radius;

        // 基于當前時間計算的角度
        // let angel = dir * BASE_SPEED * TIME_STEP * now % 360. / PI;
        let angel = formation.angle
            + dir * formation.speed * TIME_STEP / (x_radius.min(y_radius) * PI / 2.);

        // 計算目標點位
        let x_dst = x_radius * angel.cos() + x_pivot;
        let y_dst = y_radius * angel.sin() + y_pivot;

        // 計算距離
        // 兩點間的距離公式 根號下 a.x - b.x
        let dx = x_org - x_dst;
        let dy = y_org - y_dst;

        let distance = (dx * dx + dy * dy).sqrt();
        let distance_radio = if distance != 0. {
            max_distance / distance
        } else {
            0.
        };

        // 計算 x y 的最終坐標
        let x = x_org - dx * distance_radio;
        let x = if dx > 0. { x.max(x_dst) } else { x.min(x_dst) };
        let y = y_org - dy * distance_radio;
        let y = if dy > 0. { y.max(y_dst) } else { y.min(y_dst) };

        // 圖片資源在橢圓上 或接近橢圓時開始加入旋轉
        if distance < max_distance * formation.speed / 20. {
            formation.angle = angel;
        }

        let translation = &mut transform.translation;
        (translation.x, translation.y) = (x, y);
    }
}

components.rs

use bevy::{
    prelude::{Component, Vec2, Vec3},
    time::{Timer, TimerMode},
};

// 通用控制組件
#[derive(Component)]
pub struct Velocity {
    pub x: f32,
    pub y: f32,
}
impl Velocity {
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
}

/// 移動能力組件
#[derive(Component)]
pub struct Movable {
    /// 自動銷毀
    pub auto_despawn: bool,
}

/// 玩家組件
#[derive(Component)]
pub struct Player;

/// 玩家資訊組件
#[derive(Component)]
pub struct FromPlayer;

/// 敵人組件
#[derive(Component)]
pub struct Enemy;

/// 敵人資訊組件
#[derive(Component)]
pub struct FromEnemy;

/// 激光組件
#[derive(Component)]
pub struct Laser;

/// 圖片大小組件
#[derive(Component)]
pub struct SpriteSize(pub Vec2);

/// 實作 (f32,f32) 轉 SpritSize
impl From<(f32, f32)> for SpriteSize {
    fn from(value: (f32, f32)) -> Self {
        Self(Vec2::new(value.0, value.1))
    }
}

/// 爆炸組件
#[derive(Component)]
pub struct Explosion;

/// 產生爆炸組件
#[derive(Component)]
pub struct ExplosionToSpawn(pub Vec3);

/// 爆炸事件組件
#[derive(Component)]
pub struct ExplosionTimer(pub Timer);

impl Default for ExplosionTimer {
    fn default() -> Self {
        Self(Timer::from_seconds(0.05, TimerMode::Once))
    }
}

/// 分數顯示組件
#[derive(Component)]
pub struct DisplayScore;

/// 歡迎組件
#[derive(Component)]
pub struct WelcomeText;

/// 暫停組件
#[derive(Component)]
pub struct PausedText;

constants.rs

/// 游戲背景圖片路徑
pub const BACKGROUND_SPRITE: &str = "images/planet05.png";

/// 玩家圖片路徑
pub const PLAYER_SPRITE: &str = "images/player_a_01.png";
/// 玩家大小
pub const PLAYER_SIZE: (f32, f32) = (144., 75.);
/// 玩家攻擊圖片路徑
pub const PLAYER_LASER_SPRITE: &str = "images/laser_a_01.png";
/// 玩家攻擊圖片大小
pub const PLAYER_LASER_SIZE: (f32, f32) = (9., 54.);

/// 敵人圖片路徑
pub const ENEMY_SPRITE: &str = "images/enemy_a_01.png";
/// 敵人大小
pub const ENEMY_SIZE: (f32, f32) = (144., 75.);
/// 敵人攻擊圖片路徑
pub const ENEMY_LASER_SPRITE: &str = "images/laser_b_01.png";
/// 敵人攻擊圖片大小
pub const ENEMY_LASER_SIZE: (f32, f32) = (17., 55.);

/// 爆炸圖片路徑
pub const EXPLOSION_SHEET: &str = "images/explosion_a_sheet.png";
/// 爆炸圖片大小
pub const EXPLOSION_SIZE: (f32, f32) = (64., 64.);
/// 爆炸畫面幀數
pub const EXPLOSION_ANIMATION_LEN: usize = 16;

/// 圖片縮放比例
pub const SPRITE_SCALE: f32 = 0.5;

/// 步長 (幀數)
pub const TIME_STEP: f32 = 1. / 60.;
/// 基礎速度
pub const BASE_SPEED: f32 = 500.;
/// 敵人最大數量
pub const MAX_ENEMY: u32 = 2;
/// 玩家自動重生時間
pub const PLAYER_RESPAWN_DELAY: f64 = 2.;
/// 陣型內敵人最大數量
pub const FORMATION_MEMBER_MAX: u32 = 2;

/// 敵人被摧毀聲音
pub const ENEMY_EXPLOSION_AUDIO: &str = "audios/enemy_explosion.ogg";
/// 玩家被摧毀的聲音
pub const PLAYER_EXPLOSION_AUDIO: &str = "audios/player_explosion.ogg";
/// 玩家發射激光的聲音
pub const PLAYER_LASER_AUDIO: &str = "audios/player_laser.ogg";

/// 字體路徑
pub const KENNEY_BLOCK_FONT: &str = "fonts/kenney_blocks.ttf";

main.rs

use bevy::{math::Vec3Swizzles, prelude::*, sprite::collide_aabb::collide, utils::HashSet};
use components::*;

use constants::*;
use enemy::EnemyPlugin;
use player::PlayerPlugin;
use resource::{GameAudio, GameData, GameState, GameTextures, MaxEnemy, PlayerState, WinSize};
use state::StatePlugin;

mod components;
mod constants;
mod enemy;
mod player;
mod resource;
mod state;

fn main() {
    // add_startup_system 啟動生命周期時只運行一次 ,
    // add_system 每幀都會被呼叫方法
    App::new()
        .add_state::<GameState>()
        .insert_resource(ClearColor(Color::rgb(0.04, 0.04, 0.04)))
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "Invaders".to_owned(),
                resolution: (598., 676.).into(),
                position: WindowPosition::At(IVec2::new(2282, 0)),
                ..Window::default()
            }),
            ..WindowPlugin::default()
        }))
        .add_plugin(PlayerPlugin)
        .add_plugin(EnemyPlugin)
        .add_plugin(StatePlugin)
        .add_startup_system(setup_system)
        // InGame 狀態下執行的函式
        .add_systems(
            (
                laser_movable_system,
                player_laser_hit_enemy_system,
                explosion_to_spawn_system,
                explosion_animation_system,
                enemy_laser_hit_player_system,
                score_display_update_system,
            )
                .in_set(OnUpdate(GameState::InGame)),
        )
        // 啟動 esc 鍵退出程式
        .add_system(bevy::window::close_on_esc)
        .run();
}

/// 資源加載
fn setup_system(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlas>>,
    mut windows: Query<&mut Window>,
) {
    // 創建2d鏡頭
    commands.spawn(Camera2dBundle::default());

    // 獲取當前視窗
    let window = windows.single_mut();
    let win_w = window.width();
    let win_h = window.height();

    //  添加 WinSize 資源
    let win_size = WinSize { w: win_w, h: win_h };
    commands.insert_resource(win_size);

    // 創建爆炸影片
    let texture_handle = asset_server.load(EXPLOSION_SHEET);
    let texture_atlas =
        TextureAtlas::from_grid(texture_handle, Vec2::from(EXPLOSION_SIZE), 4, 4, None, None);
    let explosion = texture_atlases.add(texture_atlas);

    // 添加 GameTextures
    let game_texture = GameTextures {
        background: asset_server.load(BACKGROUND_SPRITE),
        player: asset_server.load(PLAYER_SPRITE),
        player_laser: asset_server.load(PLAYER_LASER_SPRITE),
        enemy: asset_server.load(ENEMY_SPRITE),
        enemy_laser: asset_server.load(ENEMY_LASER_SPRITE),
        font: asset_server.load(KENNEY_BLOCK_FONT),
        explosion,
    };

    // 聲音資源引入
    let game_audio = GameAudio {
        player_laser: asset_server.load(PLAYER_LASER_AUDIO),
        player_explosion: asset_server.load(PLAYER_EXPLOSION_AUDIO),
        enemy_explosion: asset_server.load(ENEMY_EXPLOSION_AUDIO),
    };

    // 背景圖片
    commands.spawn(SpriteBundle {
        texture: game_texture.background.clone(),
        sprite: Sprite {
            custom_size: Some(Vec2 { x: win_w, y: win_h }),
            ..Default::default()
        },
        transform: Transform::from_scale(Vec3::new(1.5, 1.5, 0.0)),
        ..Default::default()
    });

    // 字體引入
    let font = game_texture.font.clone();
    let text_style = TextStyle {
        font: font.clone(),
        font_size: 32.,
        color: Color::ANTIQUE_WHITE,
    };
    let text_alignment = TextAlignment::Center;

    // 分數展示控制元件
    commands.spawn((
        Text2dBundle {
            text: Text::from_section("SCORE:0", text_style).with_alignment(text_alignment),
            transform: Transform {
                translation: Vec3 {
                    x: 0.,
                    y: win_h / 2. - 20.,
                    z: 11.,
                },
                ..Default::default()
            },
            ..Default::default()
        },
        DisplayScore,
    ));

    let game_data = GameData::new();
    commands.insert_resource(game_data);
    commands.insert_resource(game_audio);
    commands.insert_resource(game_texture);
    commands.insert_resource(MaxEnemy(0));
}

/// 激光移動系統
fn laser_movable_system(
    mut commands: Commands,
    win_size: Res<WinSize>,
    mut query: Query<(Entity, &Velocity, &mut Transform, &Movable), With<Laser>>,
) {
    for (entity, velocity, mut transform, movable) in query.iter_mut() {
        // 移動位置
        let translation = &mut transform.translation;
        translation.x += velocity.x * BASE_SPEED * TIME_STEP;
        translation.y += velocity.y * BASE_SPEED * TIME_STEP;

        // 自動銷毀
        if movable.auto_despawn {
            const MARGIN: f32 = 200.;
            if translation.y > win_size.h / 2. + MARGIN
                || translation.y < -win_size.h / 2. - MARGIN
                || translation.x > win_size.w / 2. + MARGIN
                || translation.x < -win_size.w / 2. - MARGIN
            {
                commands.entity(entity).despawn();
            }
        }
    }
}

/// 敵人激光攻擊玩家判定系統
fn enemy_laser_hit_player_system(
    mut commands: Commands,
    mut player_state: ResMut<PlayerState>,
    time: Res<Time>,
    audio_source: Res<GameAudio>,
    audio: Res<Audio>,
    mut game_data: ResMut<GameData>,
    mut next_state: ResMut<NextState<GameState>>,
    laser_query: Query<(Entity, &Transform, &SpriteSize), (With<Laser>, With<FromEnemy>)>,
    player_query: Query<(Entity, &Transform, &SpriteSize), With<Player>>,
) {
    if let Ok((player_entity, player_tf, player_size)) = player_query.get_single() {
        let player_scale = Vec2::from(player_tf.scale.xy());

        for (laser, laser_tf, laser_size) in laser_query.into_iter() {
            let laser_scale = Vec2::from(laser_tf.scale.xy());

            let collision = collide(
                player_tf.translation,
                player_size.0 * player_scale,
                laser_tf.translation,
                laser_size.0 * laser_scale,
            );

            if let Some(_) = collision {
                // 播放音樂
                audio.play(audio_source.player_explosion.clone());
                // 重置分數
                game_data.reset_score();
                next_state.set(GameState::Welcome);
                // 銷毀角色
                commands.entity(player_entity).despawn();
                // 記錄被命中的時刻
                player_state.shot(time.elapsed_seconds_f64());
                // 銷毀激光
                commands.entity(laser).despawn();
                // 產生爆炸影片
                commands.spawn(ExplosionToSpawn(player_tf.translation.clone()));
                break;
            }
        }
    }
}

/// 玩家攻擊敵人判定系統
fn player_laser_hit_enemy_system(
    mut commands: Commands,
    audio_source: Res<GameAudio>,
    audio: Res<Audio>,
    mut max_enemy: ResMut<MaxEnemy>,
    mut game_data: ResMut<GameData>,
    laser_query: Query<(Entity, &Transform, &SpriteSize), (With<Laser>, With<FromPlayer>)>,
    enemy_query: Query<(Entity, &Transform, &SpriteSize), With<Enemy>>,
) {
    // 重復洗掉檢測
    let mut despawn_entities: HashSet<Entity> = HashSet::new();
    // 玩家激光
    for (laser_entity, laser_tf, laser_size) in laser_query.iter() {
        if despawn_entities.contains(&laser_entity) {
            continue;
        }

        // 玩家激光的坐標
        let laser_scale = Vec2::from(laser_tf.scale.xy());

        // 敵人
        for (enemy_entity, enemy_tf, enemy_size) in enemy_query.iter() {
            if despawn_entities.contains(&enemy_entity) || despawn_entities.contains(&laser_entity)
            {
                continue;
            }

            // 敵人坐標
            let enemy_scale = Vec2::from(enemy_tf.scale.xy());

            // collide 定義兩個元素的碰撞,a 點坐標,a 的大小,b 點坐標,b 的大小,如果未發生碰撞回傳 None
            let collision = collide(
                laser_tf.translation,
                laser_size.0 * laser_scale,
                enemy_tf.translation,
                enemy_size.0 * enemy_scale,
            );

            // 碰撞檢測
            if let Some(_) = collision {
                // 敵人數量 -1
                if max_enemy.0 != 0 {
                    max_enemy.0 -= 1;
                }
                game_data.add_score();

                audio.play(audio_source.enemy_explosion.clone());
                // 銷毀敵人
                commands.entity(enemy_entity).despawn();
                despawn_entities.insert(enemy_entity);
                // 銷毀激光
                commands.entity(laser_entity).despawn();
                despawn_entities.insert(laser_entity);

                // 播放爆炸影片
                commands.spawn(ExplosionToSpawn(enemy_tf.translation.clone()));
            }
        }
    }
}

/// 爆炸畫面生成系統
fn explosion_to_spawn_system(
    mut commands: Commands,
    game_textures: Res<GameTextures>,
    query: Query<(Entity, &ExplosionToSpawn)>,
) {
    for (explosion_spawn_entity, explosion_to_spawn) in query.iter() {
        commands
            .spawn(SpriteSheetBundle {
                texture_atlas: game_textures.explosion.clone(),
                transform: Transform {
                    translation: explosion_to_spawn.0,
                    ..Default::default()
                },
                ..Default::default()
            })
            .insert(Explosion)
            .insert(ExplosionTimer::default());

        commands.entity(explosion_spawn_entity).despawn();
    }
}

/// 爆炸影片系統
fn explosion_animation_system(
    mut commands: Commands,
    time: Res<Time>,
    mut query: Query<(Entity, &mut ExplosionTimer, &mut TextureAtlasSprite), With<Explosion>>,
) {
    for (entity, mut timer, mut texture_atlas_sprite) in query.iter_mut() {
        timer.0.tick(time.delta());

        if timer.0.finished() {
            texture_atlas_sprite.index += 1;
            if texture_atlas_sprite.index >= EXPLOSION_ANIMATION_LEN {
                commands.entity(entity).despawn();
            }
        }
    }
}

/// 分數更新系統
fn score_display_update_system(
    game_data: Res<GameData>,
    mut query: Query<&mut Text, With<DisplayScore>>,
) {
    for mut text in &mut query {
        let new_str: String = format!("SCORE:{}", game_data.get_score());
        text.sections[0].value = https://www.cnblogs.com/SantiagoZhang/archive/2023/04/19/new_str;
    }
}

player.rs

use bevy::{prelude::*, time::common_conditions::on_timer};
use std::time::Duration;

use crate::{
    components::{FromPlayer, Laser, Movable, Player, SpriteSize, Velocity},
    resource::GameAudio,
    resource::PlayerState,
    resource::WinSize,
    resource::{GameState, GameTextures},
    BASE_SPEED, PLAYER_LASER_SIZE, PLAYER_RESPAWN_DELAY, PLAYER_SIZE, SPRITE_SCALE, TIME_STEP,
};

pub struct PlayerPlugin;

impl Plugin for PlayerPlugin {
    fn build(&self, app: &mut App) {
        // add_startup_system 應用程式生命周期開始時運行一次
        // StartupSet::PostStartup 在 StartupSet::Startup 后運行一次
        // add_startup_system(player_spawn_system.in_base_set(StartupSet::PostStartup))
        // add_system 每幀都運行 , 可以在函式后通過 run_if 傳入 bool 型別的條件進行限制
        app.insert_resource(PlayerState::default())
            .add_system(
                player_spawn_system
                    .run_if(on_timer(Duration::from_secs_f32(0.5)))
                    .in_set(OnUpdate(GameState::InGame)),
            )
            .add_systems(
                (
                    player_keyboard_event_system,
                    player_movable_system,
                    player_fire_system,
                )
                    .in_set(OnUpdate(GameState::InGame)),
            );
    }
}

/// 玩家角色生成系統
fn player_spawn_system(
    mut commands: Commands,
    mut player_state: ResMut<PlayerState>,
    time: Res<Time>,
    game_textures: Res<GameTextures>,
    win_size: Res<WinSize>,
) {
    let now = time.elapsed_seconds_f64();
    let last_shot = player_state.last_shot;
    if !player_state.on && (player_state.last_shot == -1. || now - PLAYER_RESPAWN_DELAY > last_shot)
    {
        let bottom = -win_size.h / 2.;

        // 創建組件物體,并回傳對應的 EntityCommand
        commands
            .spawn(SpriteBundle {
                texture: game_textures.player.clone(),
                transform: Transform {
                    translation: Vec3::new(
                        0.,
                        bottom + PLAYER_SIZE.1 / 2. * SPRITE_SCALE + 5.0,
                        10.,
                    ),
                    scale: Vec3::new(SPRITE_SCALE, SPRITE_SCALE, 1.0),
                    ..default()
                },
                ..SpriteBundle::default()
            })
            .insert(Velocity::new(0., 0.))
            .insert(Movable {
                auto_despawn: false,
            })
            .insert(SpriteSize::from(PLAYER_SIZE))
            .insert(Player);

        player_state.spawned();
    }
}

/// 玩家攻擊系統
fn player_fire_system(
    mut commands: Commands,
    audio_source: Res<GameAudio>,
    audio: Res<Audio>,
    kb: Res<Input<KeyCode>>,
    game_textures: Res<GameTextures>,
    query: Query<&Transform, With<Player>>,
) {
    if let Ok(player_tf) = query.get_single() {
        // just_released 松開按鍵
        if kb.just_released(KeyCode::Space) {
            audio.play(audio_source.player_laser.clone());
            let (x, y) = (player_tf.translation.x, player_tf.translation.y);

            let x_offset = PLAYER_SIZE.0 / 2. * SPRITE_SCALE - 5.;

            // 激光生成閉包 因為這里使用了 commands 生成新的包 所以這里的閉包需要定義為 mut 型別
            let mut spawn_laser = |x_offset: f32| {
                commands
                    .spawn(SpriteBundle {
                        texture: game_textures.player_laser.clone(),
                        transform: Transform {
                            translation: Vec3::new(x + x_offset, y + 15., 1.),
                            scale: Vec3::new(SPRITE_SCALE, SPRITE_SCALE, 0.),
                            ..Default::default()
                        },
                        ..Default::default()
                    })
                    .insert(Laser)
                    .insert(FromPlayer)
                    .insert(SpriteSize::from(PLAYER_LASER_SIZE))
                    .insert(Movable { auto_despawn: true })
                    .insert(Velocity::new(0., 1.));
            };
            spawn_laser(x_offset);
            spawn_laser(-x_offset);
        }
    }
}

/// 鍵盤事件系統
fn player_keyboard_event_system(
    kb: Res<Input<KeyCode>>,
    mut next_state: ResMut<NextState<GameState>>,
    mut query: Query<&mut Velocity, With<Player>>,
) {
    if let Ok(mut velocity) = query.get_single_mut() {
        // pressed 按下按鍵
        if kb.pressed(KeyCode::Left) {
            velocity.x = -1.
        } else if kb.pressed(KeyCode::Right) {
            velocity.x = 1.
        } else if kb.just_pressed(KeyCode::P) {
            next_state.set(GameState::Paused);
        } else {
            velocity.x = 0.
        }
    };
}

/// 玩家移動系統
fn player_movable_system(
    win_size: Res<WinSize>,
    mut query: Query<(&Velocity, &mut Transform), With<Player>>,
) {
    let max_w = win_size.w / 2.;

    for (velocity, mut transform) in query.iter_mut() {
        let distance = velocity.x * BASE_SPEED * TIME_STEP;
        let new_x = transform.translation.x + distance;
        if -max_w <= new_x && new_x <= max_w {
            // 移動位置
            transform.translation.x += distance;
        }
    }
}

resource.rs

use bevy::{
    prelude::{AudioSource, Handle, Image, Resource, States},
    sprite::TextureAtlas,
    text::Font,
};

/// 游戲視窗大小資源
#[derive(Resource)]
pub struct WinSize {
    pub w: f32,
    pub h: f32,
}

/// 游戲影像資源
#[derive(Resource)]
pub struct GameTextures {
    pub background: Handle<Image>,
    pub player: Handle<Image>,
    pub player_laser: Handle<Image>,
    pub enemy: Handle<Image>,
    pub enemy_laser: Handle<Image>,
    pub explosion: Handle<TextureAtlas>,
    pub font: Handle<Font>,
}

/// 敵人最大數量
#[derive(Resource)]
pub struct MaxEnemy(pub u32);

/// 玩家狀態
#[derive(Resource)]
pub struct PlayerState {
    pub on: bool,
    pub last_shot: f64,
}

impl Default for PlayerState {
    fn default() -> Self {
        Self {
            on: false,
            last_shot: -1.,
        }
    }
}

impl PlayerState {
    /// 被命中
    pub fn shot(&mut self, time: f64) {
        self.on = false;
        self.last_shot = time;
    }
    /// 重生
    pub fn spawned(&mut self) {
        self.on = true;
        self.last_shot = -1.;
    }
}

#[derive(Resource)]
pub struct GameAudio {
    pub enemy_explosion: Handle<AudioSource>,
    pub player_explosion: Handle<AudioSource>,
    pub player_laser: Handle<AudioSource>,
}

/// 游戲狀態    
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Hash, States)]
pub enum GameState {
    /// 歡迎
    #[default]
    Welcome,
    /// 游戲中
    InGame,
    /// 暫停
    Paused,
}

/// 游戲資料
#[derive(Resource)]
pub struct GameData {
    score: u32,
}

impl GameData {
    pub fn new() -> Self {
        Self { score: 0 }
    }

    /// 獲取當前得分
    pub fn get_score(&self) -> u32 {
        self.score
    }

    /// 增加得分
    pub fn add_score(&mut self) {
        self.score += 1;
    }

    /// 增加得分
    pub fn reset_score(&mut self) {
        self.score = 0;
    }
}

state.rs

use bevy::{
    prelude::{
        Color, Commands, Entity, Input, IntoSystemAppConfig, IntoSystemConfig, IntoSystemConfigs,
        KeyCode, NextState, OnEnter, OnExit, OnUpdate, Plugin, Query, Res, ResMut, Transform, Vec3,
        With,
    },
    text::{Text, Text2dBundle, TextAlignment, TextSection, TextStyle},
    time::Time,
};

use crate::{
    components::{PausedText, WelcomeText},
    resource::{GameState, GameTextures},
};

pub struct StatePlugin;
impl Plugin for StatePlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        app
            // 在 CoreSet::StateTransitions 期間,當 AppState::Menu 時,該函式執行,
            //當退出該狀態進入下一個狀態時,會先執行當前狀態的退出函式,再執行下個狀態的函式
            // OnEnter 進入時執行、OnUpdate 期間內每幀執行、OnExit 退出時執行
            .add_system(welcome_system.in_schedule(OnEnter(GameState::Welcome)))
            // CoreSet::Update 期間 主函式中的 on_update 將會檢查 State 資源的值,并判斷是否應該運行
            .add_systems(
                (welcome_input_system, welcome_text_scale_system)
                    .in_set(OnUpdate(GameState::Welcome)),
            )
            .add_system(welcome_exit_system.in_schedule(OnExit(GameState::Welcome)))
            // Paused 狀態下執行的函式
            .add_system(paused_system.in_schedule(OnEnter(GameState::Paused)))
            .add_system(paused_input_system.in_set(OnUpdate(GameState::Paused)))
            .add_system(paused_exit_system.in_schedule(OnExit(GameState::Paused)));
    }
}

/// 歡迎狀態下運行的系統
pub fn welcome_system(mut commands: Commands, game_textures: Res<GameTextures>) {
    // 字體引入
    let font = game_textures.font.clone();
    let text_style = TextStyle {
        font: font.clone(),
        font_size: 46.,
        color: Color::BLUE,
    };
    let text_alignment = TextAlignment::Center;

    let text = Text {
        sections: vec![
            TextSection::new("PRESS ", text_style.clone()),
            TextSection::new(
                " ENTER ",
                TextStyle {
                    color: Color::RED,
                    ..text_style.clone()
                },
            ),
            TextSection::new("START GAME !\r\n", text_style.clone()),
            TextSection::new("PRESS ", text_style.clone()),
            TextSection::new(
                " P ",
                TextStyle {
                    color: Color::RED,
                    ..text_style.clone()
                },
            ),
            TextSection::new("TO PAUSED GAME !", text_style.clone()),
        ],
        ..Default::default()
    }
    .with_alignment(text_alignment);
    commands.spawn((
        Text2dBundle {
            text,
            transform: Transform {
                translation: Vec3 {
                    x: 0.,
                    y: -20.,
                    z: 11.,
                },
                ..Default::default()
            },
            ..Default::default()
        },
        WelcomeText,
    ));
}

/// 歡迎狀態狀態下的鍵盤監聽系統
pub fn welcome_input_system(kb: Res<Input<KeyCode>>, mut next_state: ResMut<NextState<GameState>>) {
    if kb.just_pressed(KeyCode::Return) {
        next_state.set(GameState::InGame);
    }
}

/// 歡迎狀態字體變化系統
pub fn welcome_text_scale_system(
    time: Res<Time>,
    mut query: Query<&mut Transform, (With<Text>, With<WelcomeText>)>,
) {
    for mut transform in &mut query {
        transform.scale = Vec3::splat(time.elapsed_seconds().sin() / 4. + 0.9);
    }
}

/// 退出歡迎狀態時執行的系統
pub fn welcome_exit_system(
    mut commands: Commands,
    query: Query<Entity, (With<Text>, With<WelcomeText>)>,
) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
}

/// 暫停狀態下運行的系統
pub fn paused_system(mut commands: Commands, game_textures: Res<GameTextures>) {
    // 字體引入
    let font = game_textures.font.clone();
    let text_style = TextStyle {
        font: font.clone(),
        font_size: 46.,
        color: Color::BLUE,
    };
    let text_alignment = TextAlignment::Center;

    let text = Text {
        sections: vec![
            TextSection::new("GAME PAUSED!\r\nPRESSED", text_style.clone()),
            TextSection::new(
                " R ",
                TextStyle {
                    color: Color::RED,
                    ..text_style.clone()
                },
            ),
            TextSection::new("RETURN GAME!", text_style.clone()),
        ],
        ..Default::default()
    }
    .with_alignment(text_alignment);
    commands.spawn((
        Text2dBundle {
            text,
            transform: Transform {
                translation: Vec3 {
                    x: 0.,
                    y: -20.,
                    z: 11.,
                },
                ..Default::default()
            },
            ..Default::default()
        },
        PausedText,
    ));
}

/// 暫停狀態狀態下的鍵盤監聽系統
pub fn paused_input_system(kb: Res<Input<KeyCode>>, mut next_state: ResMut<NextState<GameState>>) {
    if kb.pressed(KeyCode::R) {
        next_state.set(GameState::InGame);
    }
}

/// 退出暫停狀態時執行的系統
pub fn paused_exit_system(
    mut commands: Commands,
    query: Query<Entity, (With<Text>, With<PausedText>)>,
) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
}

about me

目前失業,在家學習 rust ,

我的 bilibili,我的 GitHub,

Rust官網
Rust 中文社區

本文來自博客園,作者:賢云曳賀,轉載請注明原文鏈接:https://www.cnblogs.com/SantiagoZhang/p/17334165.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/550530.html

標籤:其他

上一篇:推排序 Verilog實作原理

下一篇:簡單介紹十幾款常用的畫架構圖流程圖的軟體

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more