主頁 > 後端開發 > 一個簡單的 rust 專案 使用 bevy 引擎 復刻 Flappy Bird 小游戲

一個簡單的 rust 專案 使用 bevy 引擎 復刻 Flappy Bird 小游戲

2023-04-25 07:46:30 後端開發

Rust + Bevy 實作的 Flappy Bird 游戲

簡介

一個使用 bevy 引擎復刻的 Flappy Bird 經典小游戲,
通過該專案我們可以學到:bevy 的自定義組件,自定義插件,自定義資源,sprite 的旋轉,sprite 的移動,sprite sheet 影片的定義使用,狀態管理,等內容…

簡單介紹一下包含的內容:

  • 游戲狀態管理 Menu、InGame、Paused、GameOver,
  • 小鳥碰撞檢測,
  • 地面移動,
  • 小鳥飛翔影片,
  • 小鳥飛行方向變化,
  • 小鳥重力系統,
  • 障礙物隨機生成,

通過空格向上飛行,
按 P 暫停游戲,按 R 恢復游戲,

代碼結構

·
├── assets/
│   ├──audios/
│   ├──fonts/
│   └──images/
├── src/
│   ├── build.rs
│   ├── components.rs
│   ├── constants.rs
│   ├── main.rs
│   ├── obstacle.rs
│   ├── player.rs
│   ├── resource.rs
│   └── state.rs
├── Cargo.lock
└── Cargo.toml
  • assets/audios 聲音資源檔案,
  • assets/fonts 字體資源檔案,
  • assets/images 圖片資源檔案,
  • build.rs 構建之前執行的腳本檔案,
  • components.rs 游戲組件定義,
  • constants.rs 負責存盤游戲中用到的常量,
  • main.rs 負責游戲的邏輯、插件互動、等內容,
  • obstacle.rs 障礙物生成、初始化,
  • player.rs 玩家角色插件,生成、移動、鍵盤處理的實作,
  • resource.rs 游戲資源定義,
  • state.rs 游戲狀態管理,

build.rs

use std::{
    env, fs,
    path::{Path, PathBuf},
};

const COPY_DIR: &'static str = "assets";

/// A helper function for recursively copying a directory.
fn copy_dir<P, Q>(from: P, to: Q)
where
    P: AsRef<Path>,
    Q: AsRef<Path>,
{
    let to = to.as_ref().to_path_buf();

    for path in fs::read_dir(from).unwrap() {
        let path = path.unwrap().path();
        let to = to.clone().join(path.file_name().unwrap());

        if path.is_file() {
            fs::copy(&path, to).unwrap();
        } else if path.is_dir() {
            if !to.exists() {
                fs::create_dir(&to).unwrap();
            }

            copy_dir(&path, to);
        } else { /* Skip other content */
        }
    }
}

fn main() {
    // Request the output directory
    let out = env::var("PROFILE").unwrap();
    let out = PathBuf::from(format!("target/{}/{}", out, COPY_DIR));

    // If it is already in the output directory, delete it and start over
    if out.exists() {
        fs::remove_dir_all(&out).unwrap();
    }

    // Create the out directory
    fs::create_dir(&out).unwrap();

    // Copy the directory
    copy_dir(COPY_DIR, &out);
}

components.rs

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

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

/// 玩家影片播放計時器
#[derive(Component)]
pub struct PlayerAnimationTimer(pub Timer);

impl Default for PlayerAnimationTimer {
    fn default() -> Self {
        Self(Timer::from_seconds(0.1, TimerMode::Repeating))
    }
}

/// 障礙物組件
#[derive(Component)]
pub struct Obstacle;

/// 移動組件
#[derive(Component)]
pub struct Movable {
    /// 移動時是否需要旋轉
    pub need_rotation: bool,
}

impl Default for Movable {
    fn default() -> Self {
        Self {
            need_rotation: false,
        }
    }
}

/// 速度組件
#[derive(Component)]
pub struct Velocity {
    pub x: f32,
    pub y: f32,
}

impl Default for Velocity {
    fn default() -> Self {
        Self { x: 0., y: 0. }
    }
}

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

/// 選單顯示組件
#[derive(Component)]
pub struct DisplayMenu;

/// 地面組件
#[derive(Component)]
pub struct Ground(pub f32);

/// 游戲結束組件
#[derive(Component)]
pub struct DisplayGameOver;

constants.rs

/// 小鳥圖片路徑
pub const BIRD_IMG_PATH: &str = "images/bird_columns.png";
/// 小鳥圖片大小
pub const BIRD_IMG_SIZE: (f32, f32) = (34., 24.);
/// 小鳥影片幀數
pub const BIRD_ANIMATION_LEN: usize = 3;

pub const WINDOW_WIDTH: f32 = 576.;
pub const WINDOW_HEIGHT: f32 = 624.;

/// 背景圖片路徑
pub const BACKGROUND_IMG_PATH: &str = "images/background.png";
/// 背景圖片大小
pub const BACKGROUND_IMG_SIZE: (f32, f32) = (288., 512.);
/// 地面圖片路徑
pub const GROUND_IMG_PATH: &str = "images/ground.png";
/// 地面圖片大小
pub const GROUND_IMG_SIZE: (f32, f32) = (336., 112.);
/// 一個單位地面的大小
pub const GROUND_ITEM_SIZE: f32 = 48.;
/// 管道圖片路徑
pub const PIPE_IMG_PATH: &str = "images/pipe.png";
/// 管道圖片大小
pub const PIPE_IMG_SIZE: (f32, f32) = (52., 320.);
/// 飛翔聲音路徑
pub const FLAY_AUDIO_PATH: &str = "audios/wing.ogg";
/// 得分聲音
pub const POINT_AUDIO_PATH: &str = "audios/point.ogg";
/// 死亡聲音
pub const DIE_AUDIO_PATH: &str = "audios/die.ogg";
/// 被撞擊聲音
pub const HIT_AUDIO_PATH: &str = "audios/hit.ogg";
/// kenney future 字體路徑
pub const KENNEY_FUTURE_FONT_PATH: &str = "fonts/KenneyFuture.ttf";

/// x 軸前進速度
pub const SPAWN_OBSTACLE_TICK: f32 = 4.;
/// x 軸前進速度
pub const PLAYER_X_MAX_VELOCITY: f32 = 48.;
/// y 軸最大上升速度
pub const PLAYER_Y_MAX_UP_VELOCITY: f32 = 20.;
/// y 軸每次上升像素
pub const PLAYER_Y_UP_PIXEL: f32 = 10.;
/// y 軸最大下落速度
pub const PLAYER_Y_MAX_VELOCITY: f32 = 200.;
/// y 軸下落加速度,每秒增加
pub const GRAVITY_VELOCITY: f32 = 80.;
/// 步長 (幀數)
pub const TIME_STEP: f32 = 1. / 60.;

/// 最大通過空間
pub const GAP_MAX: f32 = 300.;
/// 最小通過空間
pub const GAP_MIN: f32 = 50.;

main.rs

use bevy::{
    prelude::*,
    sprite::collide_aabb::collide,
    window::{Window, WindowPlugin, WindowPosition},
};
use obstacle::ObstaclePlugin;

use components::{DisplayScore, Ground, Movable, Obstacle, Player, PlayerAnimationTimer, Velocity};
use constants::*;
use player::PlayerPlugin;
use resource::{GameData, StaticAssets, WinSize};
use state::{GameState, StatesPlugin};

mod components;
mod constants;
mod obstacle;
mod player;
mod resource;
mod state;

fn main() {
    App::new()
        .add_state::<GameState>()
        .insert_resource(ClearColor(Color::rgb_u8(205, 201, 201)))
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "Flappy Bird".to_owned(),
                resolution: (WINDOW_WIDTH, WINDOW_HEIGHT).into(),
                position: WindowPosition::At(IVec2::new(2282, 0)),
                resizable: false,
                ..Default::default()
            }),
            ..Default::default()
        }))
        .add_system(system_startup.on_startup())
        .add_plugin(StatesPlugin)
        .add_plugin(PlayerPlugin)
        .add_plugin(ObstaclePlugin)
        .add_systems(
            (
                score_display_update_system,
                player_animation_system,
                player_score_system,
                movable_system,
                ground_move_system,
                player_collision_check_system,
            )
                .in_set(OnUpdate(GameState::InGame)),
        )
        .add_system(bevy::window::close_on_esc)
        .run();
}

/// 玩家碰撞檢測系統
fn player_collision_check_system(
    win_size: Res<WinSize>,
    static_assets: Res<StaticAssets>,
    audio_player: Res<Audio>,
    mut next_state: ResMut<NextState<GameState>>,
    obstacle_query: Query<(Entity, &Transform), With<Obstacle>>,
    player_query: Query<(Entity, &Transform), With<Player>>,
) {
    let player_result = player_query.get_single();
    match player_result {
        Ok((_, player_tf)) => {
            let mut is_collision = false;
            // 先進行邊緣碰撞檢測
            if player_tf.translation.y >= win_size.height / 2.
                || player_tf.translation.y <= -(win_size.height / 2. - GROUND_IMG_SIZE.1)
            {
                is_collision = true;
            }

            for (_, obstacle_tf) in obstacle_query.iter() {
                let collision = collide(
                    player_tf.translation,
                    Vec2 {
                        x: BIRD_IMG_SIZE.0,
                        y: BIRD_IMG_SIZE.1,
                    },
                    obstacle_tf.translation,
                    Vec2 {
                        x: PIPE_IMG_SIZE.0,
                        y: PIPE_IMG_SIZE.1,
                    },
                );
                if let Some(_) = collision {
                    is_collision = true;
                    break;
                }
            }
            // 判斷是否已經發生碰撞
            if is_collision {
                // 增加得分并播放聲音
                audio_player.play(static_assets.hit_audio.clone());
                audio_player.play(static_assets.die_audio.clone());
                next_state.set(GameState::GameOver);
            }
        }
        _ => (),
    }
}

/// 玩家得分檢測
fn player_score_system(
    mut commands: Commands,
    mut game_data: ResMut<GameData>,
    static_assets: Res<StaticAssets>,
    audio_player: Res<Audio>,
    obstacle_query: Query<(Entity, &Transform), With<Obstacle>>,
    player_query: Query<(Entity, &Transform), With<Player>>,
) {
    let player_result = player_query.get_single();
    match player_result {
        Ok((_, player_tf)) => {
            let mut need_add_score = false;
            for (entity, obstacle_tf) in obstacle_query.iter() {
                // 鳥的 尾巴通過管道的右邊緣
                if player_tf.translation.x - BIRD_IMG_SIZE.0 / 2.
                    > obstacle_tf.translation.x + PIPE_IMG_SIZE.0 / 2.
                {
                    // 通過的話,將需要得分記為 true 并銷毀管道
                    need_add_score = true;
                    commands.entity(entity).despawn();
                }
            }
            // 判斷是否需要增加得分
            if need_add_score {
                // 增加得分并播放聲音
                game_data.add_score();
                audio_player.play(static_assets.point_audio.clone());
                game_data.call_obstacle_spawn();
            }
        }
        _ => (),
    }
}

/// 移動系統
///
/// * 不考慮正負值,只做加法,需要具體的物體通過移動的方向自行考慮正負值
fn movable_system(
    mut query: Query<(&mut Transform, &Velocity, &Movable), (With<Movable>, With<Velocity>)>,
) {
    for (mut transform, velocity, movable) in query.iter_mut() {
        let x = velocity.x * TIME_STEP;
        let y = velocity.y * TIME_STEP;
        transform.translation.x += x;
        transform.translation.y += y;
        // 判斷是否需要旋轉
        if movable.need_rotation {
            if velocity.y > 0. {
                transform.rotation = Quat::from_rotation_z(velocity.y / PLAYER_Y_MAX_UP_VELOCITY);
            } else {
                transform.rotation = Quat::from_rotation_z(velocity.y / PLAYER_Y_MAX_VELOCITY);
            };
        }
    }
}

/// 地面移動組件
fn ground_move_system(mut query: Query<(&mut Transform, &mut Ground)>) {
    let result = query.get_single_mut();
    match result {
        Ok((mut transform, mut ground)) => {
            ground.0 += 1.;
            transform.translation.x = -ground.0;
            ground.0 = ground.0 % GROUND_ITEM_SIZE;
        }
        _ => (),
    }
}

/// 角色影片系統
fn player_animation_system(
    time: Res<Time>,
    mut query: Query<(&mut PlayerAnimationTimer, &mut TextureAtlasSprite)>,
) {
    for (mut timer, mut texture_atlas_sprite) in query.iter_mut() {
        timer.0.tick(time.delta());
        if timer.0.just_finished() {
            let next_index = (texture_atlas_sprite.index + 1) % BIRD_ANIMATION_LEN;
            texture_atlas_sprite.index = next_index;
        }
    }
}

/// 分數更新系統
fn score_display_update_system(
    game_data: Res<GameData>,
    mut query: Query<&mut Text, With<DisplayScore>>,
) {
    for mut text in &mut query {
        text.sections[1].value = game_data.get_score().to_string();
    }
}

fn system_startup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlas>>,
    windows: Query<&Window>,
) {
    commands.spawn(Camera2dBundle::default());

    let game_data = GameData::new();
    commands.insert_resource(game_data);

    let window = windows.single();
    let (window_w, window_h) = (window.width(), window.height());
    let win_size = WinSize {
        width: window_w,
        height: window_h,
    };
    commands.insert_resource(win_size);

    let player_handle = asset_server.load(BIRD_IMG_PATH);

    // 將 player_handle 加載的圖片,用 BIRD_IMG_SIZE 的大小,按照 1 列,3 行,切圖,
    let texture_atlas =
        TextureAtlas::from_grid(player_handle, Vec2::from(BIRD_IMG_SIZE), 1, 3, None, None);
    let player = texture_atlases.add(texture_atlas);

    let background = asset_server.load(BACKGROUND_IMG_PATH);
    let pipe = asset_server.load(PIPE_IMG_PATH);
    let ground = asset_server.load(GROUND_IMG_PATH);
    let fly_audio = asset_server.load(FLAY_AUDIO_PATH);
    let die_audio = asset_server.load(DIE_AUDIO_PATH);
    let point_audio = asset_server.load(POINT_AUDIO_PATH);
    let hit_audio = asset_server.load(HIT_AUDIO_PATH);
    let kenney_future_font = asset_server.load(KENNEY_FUTURE_FONT_PATH);

    let static_assets = StaticAssets {
        player,
        background,
        pipe,
        ground,
        fly_audio,
        die_audio,
        point_audio,
        hit_audio,
        kenney_future_font,
    };
    commands.insert_resource(static_assets);

    let (background_w, background_h) = BACKGROUND_IMG_SIZE;
    let (ground_w, ground_h) = GROUND_IMG_SIZE;
    commands.spawn(SpriteBundle {
        texture: asset_server.load(BACKGROUND_IMG_PATH),
        sprite: Sprite {
            custom_size: Some(Vec2 {
                x: background_w * 2.,
                y: background_h,
            }),
            ..Default::default()
        },
        transform: Transform {
            translation: Vec3 {
                x: 0.,
                y: ground_h / 2.,
                z: 1.,
            },
            ..Default::default()
        },
        ..Default::default()
    });

    commands.spawn((
        SpriteBundle {
            texture: asset_server.load(GROUND_IMG_PATH),
            sprite: Sprite {
                custom_size: Some(Vec2 {
                    x: ground_w * 2.,
                    y: ground_h,
                }),
                ..Default::default()
            },
            transform: Transform {
                translation: Vec3 {
                    x: 0.,
                    y: window_h / 2. - background_h - ground_h / 2.,
                    z: 4.,
                },
                ..Default::default()
            },

            ..Default::default()
        },
        Ground(GROUND_ITEM_SIZE),
    ));
}

obstacle.rs

use rand::{thread_rng, Rng};
use std::time::Duration;

use crate::{
    components::{Movable, Obstacle, Velocity},
    constants::{
        BACKGROUND_IMG_SIZE, GAP_MAX, GAP_MIN, GROUND_IMG_SIZE, PIPE_IMG_SIZE,
        PLAYER_X_MAX_VELOCITY, SPAWN_OBSTACLE_TICK,
    },
    resource::{GameData, StaticAssets, WinSize},
    state::GameState,
};

use bevy::{
    prelude::{
        Commands, Entity, IntoSystemAppConfig, IntoSystemConfig, OnEnter, OnUpdate, Plugin, Query,
        Res, ResMut, Transform, Vec3, With,
    },
    sprite::{Sprite, SpriteBundle},
    time::common_conditions::on_timer,
};

/// 障礙物插件
pub struct ObstaclePlugin;

impl Plugin for ObstaclePlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        app.add_system(obstacle_init_system.in_schedule(OnEnter(GameState::InGame)))
            .add_system(
                spawn_obstacle_system
                    .run_if(on_timer(Duration::from_secs_f32(0.2)))
                    .in_set(OnUpdate(GameState::InGame)),
            );
    }
}

/// 障礙物初始化
fn obstacle_init_system(
    mut commands: Commands,
    static_assets: Res<StaticAssets>,
    win_size: Res<WinSize>,
    game_data: Res<GameData>,
    query: Query<Entity, With<Obstacle>>,
) {
    let count = query.iter().count();
    if count >= 4 {
        return;
    }

    let mut rng = thread_rng();
    // 初始 x 坐標
    let x = win_size.width / 2. + PIPE_IMG_SIZE.0 / 2.;
    // 初始化 管道區域的中心點,因為要排除地面的高度
    let center_y = (win_size.height - BACKGROUND_IMG_SIZE.1) / 2.;
    // 定義合理范圍
    let reasonable_y_max = win_size.height / 2. - 100.;
    let reasonable_y_min = -(win_size.height / 2. - 100. - GROUND_IMG_SIZE.1);

    let size = SPAWN_OBSTACLE_TICK * PLAYER_X_MAX_VELOCITY;

    for i in 0..2 {
        let x = x - PIPE_IMG_SIZE.0 - size * i as f32;
        // y軸 隨機中心點
        // 隨機可通過區域的中心點
        let point_y = rng.gen_range(reasonable_y_min..reasonable_y_max);
        let half_distance = (center_y - point_y).abs() / 2.;

        // 獲取得分 , 并根據得分獲取一個隨機的可通過區域的大小
        let score = game_data.get_score();
        let max = GAP_MAX - score as f32 / 10.;
        // 不讓 max 小于最小值
        // 這里也可以做些其他的判斷,改變下別的資料,比如說 讓管道的移動速度變快!
        let max = max.max(GAP_MIN);
        let min = GAP_MIN;
        let gap = rng.gen_range(min.min(max)..min.max(max));
        let rand_half_gap = gap * rng.gen_range(0.3..0.7);
        // 通過中心點,可通過區域,以及管道的高來計算 上下兩個管道各自中心點的 y 坐標
        let half_pipe = PIPE_IMG_SIZE.1 / 2.;
        let pipe_upper = center_y + half_distance + (rand_half_gap + half_pipe);
        let pipe_down = center_y - half_distance - (gap - rand_half_gap + half_pipe);

        // 下方水管
        commands.spawn((
            SpriteBundle {
                texture: static_assets.pipe.clone(),
                transform: Transform {
                    translation: Vec3 {
                        x,
                        y: pipe_down,
                        z: 2.,
                    },
                    ..Default::default()
                },
                ..Default::default()
            },
            Velocity {
                x: -PLAYER_X_MAX_VELOCITY,
                y: 0.,
            },
            Movable {
                need_rotation: false,
            },
            Obstacle,
        ));

        // 上方水管
        commands.spawn((
            SpriteBundle {
                texture: static_assets.pipe.clone(),
                transform: Transform {
                    translation: Vec3 {
                        x,
                        y: pipe_upper,
                        z: 2.,
                    },
                    ..Default::default()
                },
                sprite: Sprite {
                    flip_y: true,
                    ..Default::default()
                },
                ..Default::default()
            },
            Velocity {
                x: -PLAYER_X_MAX_VELOCITY,
                y: 0.,
            },
            Movable {
                need_rotation: false,
            },
            Obstacle,
        ));
    }
}

fn spawn_obstacle_system(
    mut commands: Commands,
    mut game_data: ResMut<GameData>,
    static_assets: Res<StaticAssets>,
    win_size: Res<WinSize>,
) {
    if !game_data.need_spawn_obstacle() {
        return;
    }
    game_data.obstacle_call_back();
    let mut rng = thread_rng();
    // 初始 x 坐標
    let x = win_size.width / 2. + PIPE_IMG_SIZE.0 / 2.;
    // 初始化 管道區域的中心點,因為要排除地面的高度
    let center_y = (win_size.height - BACKGROUND_IMG_SIZE.1) / 2.;

    // y軸 隨機中心點
    // 定義合理范圍
    let reasonable_y_max = win_size.height / 2. - 100.;
    let reasonable_y_min = -(win_size.height / 2. - 100. - GROUND_IMG_SIZE.1);
    // 隨機可通過區域的中心點
    let point_y = rng.gen_range(reasonable_y_min..reasonable_y_max);
    let half_distance = (center_y - point_y).abs() / 2.;

    // 獲取得分 , 并根據得分獲取一個隨機的可通過區域的大小
    let score = game_data.get_score();
    let max = GAP_MAX - score as f32 / 10.;
    // 不讓 max 小于最小值
    // 這里也可以做些其他的判斷,改變下別的資料,比如說 讓管道的移動速度變快!
    let max = max.max(GAP_MIN);
    let min = GAP_MIN;
    let gap = rng.gen_range(min.min(max)..min.max(max));
    let rand_half_gap = gap * rng.gen_range(0.3..0.7);
    // 通過中心點,可通過區域,以及管道的高來計算 上下兩個管道各自中心點的 y 坐標
    let half_pipe = PIPE_IMG_SIZE.1 / 2.;
    let pipe_upper = center_y + half_distance + (rand_half_gap + half_pipe);
    let pipe_down = center_y - half_distance - (gap - rand_half_gap + half_pipe);

    // 下方水管
    commands.spawn((
        SpriteBundle {
            texture: static_assets.pipe.clone(),
            transform: Transform {
                translation: Vec3 {
                    x,
                    y: pipe_down,
                    z: 2.,
                },
                ..Default::default()
            },
            ..Default::default()
        },
        Velocity {
            x: -PLAYER_X_MAX_VELOCITY,
            y: 0.,
        },
        Movable {
            need_rotation: false,
        },
        Obstacle,
    ));

    // 上方水管
    commands.spawn((
        SpriteBundle {
            texture: static_assets.pipe.clone(),
            transform: Transform {
                translation: Vec3 {
                    x,
                    y: pipe_upper,
                    z: 2.,
                },
                ..Default::default()
            },
            sprite: Sprite {
                flip_y: true,
                ..Default::default()
            },
            ..Default::default()
        },
        Velocity {
            x: -PLAYER_X_MAX_VELOCITY,
            y: 0.,
        },
        Movable {
            need_rotation: false,
        },
        Obstacle,
    ));
}

player.rs

use bevy::{
    prelude::{
        Audio, Commands, Input, IntoSystemAppConfig, IntoSystemConfigs, KeyCode, OnEnter, OnUpdate,
        Plugin, Query, Res, ResMut, Transform, Vec3, With,
    },
    sprite::{SpriteSheetBundle, TextureAtlasSprite},
    time::{Timer, TimerMode},
};

use crate::{
    components::{Movable, Player, PlayerAnimationTimer, Velocity},
    constants::{
        GRAVITY_VELOCITY, PLAYER_Y_MAX_UP_VELOCITY, PLAYER_Y_MAX_VELOCITY, PLAYER_Y_UP_PIXEL,
        TIME_STEP,
    },
    resource::{GameData, StaticAssets, WinSize},
    state::GameState,
};

pub struct PlayerPlugin;

impl Plugin for PlayerPlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        app.add_systems(
            (input_key_system, bird_automatic_system).in_set(OnUpdate(GameState::InGame)),
        )
        .add_system(spawn_bird_system.in_schedule(OnEnter(GameState::InGame)));
    }
}

/// 產生玩家
fn spawn_bird_system(
    mut commands: Commands,
    win_size: Res<WinSize>,
    static_assets: Res<StaticAssets>,
    mut game_data: ResMut<GameData>,
) {
    if !game_data.player_alive() {
        let bird = static_assets.player.clone();
        let (x, y) = (-win_size.width / 4. / 2., win_size.height / 2. / 3.);
        commands.spawn((
            SpriteSheetBundle {
                texture_atlas: bird,
                transform: Transform {
                    translation: Vec3 { x, y, z: 2. },
                    ..Default::default()
                },
                sprite: TextureAtlasSprite::new(0),
                ..Default::default()
            },
            Player,
            Velocity { x: 0., y: 0. },
            Movable {
                need_rotation: true,
            },
            PlayerAnimationTimer(Timer::from_seconds(0.2, TimerMode::Repeating)),
        ));
        game_data.alive();
    }
}

/// 游戲中鍵盤事件系統
fn input_key_system(
    kb: Res<Input<KeyCode>>,
    static_assets: Res<StaticAssets>,
    audio_player: Res<Audio>,
    mut query: Query<(&mut Velocity, &mut Transform), With<Player>>,
) {
    if kb.just_released(KeyCode::Space) {
        let vt = query.get_single_mut();
        // 松開空格后,直接向上20像素,并且給一個向上的速度,
        match vt {
            Ok((mut velocity, mut transform)) => {
                transform.translation.y += PLAYER_Y_UP_PIXEL;
                velocity.y = PLAYER_Y_MAX_UP_VELOCITY;
            }
            _ => (),
        }
        audio_player.play(static_assets.fly_audio.clone());
    }
}

/// 小鳥重力系統
fn bird_automatic_system(mut query: Query<&mut Velocity, (With<Player>, With<Movable>)>) {
    for mut velocity in query.iter_mut() {
        velocity.y = velocity.y - GRAVITY_VELOCITY * TIME_STEP;
        if velocity.y < -PLAYER_Y_MAX_VELOCITY {
            velocity.y = -PLAYER_Y_MAX_VELOCITY;
        }
    }
}

resource.rs

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

/// 游戲資料資源
#[derive(Resource)]
pub struct GameData {
    score: u8,
    alive: bool,
    need_add_obstacle: bool,
}
impl GameData {
    pub fn new() -> Self {
        Self {
            score: 0,
            alive: false,
            need_add_obstacle: false,
        }
    }

    pub fn need_spawn_obstacle(&self) -> bool {
        self.need_add_obstacle
    }

    pub fn obstacle_call_back(&mut self) {
        self.need_add_obstacle = false;
    }

    pub fn call_obstacle_spawn(&mut self) {
        self.need_add_obstacle = true;
    }

    pub fn alive(&mut self) {
        self.alive = true;
    }

    pub fn death(&mut self) {
        self.alive = false;
        self.score = 0;
    }

    pub fn get_score(&self) -> u8 {
        self.score
    }

    pub fn add_score(&mut self) {
        self.score += 1;
    }

    pub fn player_alive(&self) -> bool {
        self.alive
    }
}

/// 視窗大小資源
#[derive(Resource)]
pub struct WinSize {
    pub width: f32,
    pub height: f32,
}

/// 靜態資源
#[derive(Resource)]
pub struct StaticAssets {
    /* 圖片 */
    /// 玩家影片
    pub player: Handle<TextureAtlas>,
    /// 管道圖片
    pub pipe: Handle<Image>,
    /// 背景圖片
    pub background: Handle<Image>,
    /// 地面圖片
    pub ground: Handle<Image>,

    /* 聲音 */
    /// 飛行聲音
    pub fly_audio: Handle<AudioSource>,
    /// 死亡聲音
    pub die_audio: Handle<AudioSource>,
    /// 得分聲音
    pub point_audio: Handle<AudioSource>,
    /// 被撞擊聲音
    pub hit_audio: Handle<AudioSource>,

    /* 字體 */
    /// 游戲字體
    pub kenney_future_font: Handle<Font>,
}

state.rs

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

use crate::{
    components::{DisplayGameOver, DisplayMenu, DisplayScore, Obstacle, Player},
    constants::GROUND_IMG_SIZE,
    resource::{GameData, StaticAssets, WinSize},
};

#[derive(Debug, Default, States, PartialEq, Eq, Clone, Hash)]
pub enum GameState {
    #[default]
    Menu,
    InGame,
    Paused,
    GameOver,
}

pub struct StatesPlugin;

impl Plugin for StatesPlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        app
            //選單狀態
            .add_system(menu_display_system.in_schedule(OnEnter(GameState::Menu)))
            .add_system(enter_game_system.in_set(OnUpdate(GameState::Menu)))
            .add_system(exit_menu.in_schedule(OnExit(GameState::Menu)))
            // 暫停狀態
            .add_system(enter_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)))
            // 游戲中狀態
            .add_system(in_game_display_system.in_schedule(OnEnter(GameState::InGame)))
            .add_system(in_game_input_system.in_set(OnUpdate(GameState::InGame)))
            .add_system(exit_game_system.in_schedule(OnExit(GameState::InGame)))
            // 游戲結束狀態
            .add_system(game_over_enter_system.in_schedule(OnEnter(GameState::GameOver)))
            .add_system(in_game_over_system.in_set(OnUpdate(GameState::GameOver)))
            .add_system(game_over_exit_system.in_schedule(OnExit(GameState::GameOver)));
    }
}

//// 進入選單頁面
fn menu_display_system(mut commands: Commands, static_assets: Res<StaticAssets>) {
    let font = static_assets.kenney_future_font.clone();
    let common_style = TextStyle {
        font: font.clone(),
        font_size: 32.,
        color: Color::BLUE,
        ..Default::default()
    };
    let special_style = TextStyle {
        font: font.clone(),
        font_size: 38.,
        color: Color::RED,
        ..Default::default()
    };

    let align = TextAlignment::Center;
    commands.spawn((
        Text2dBundle {
            text: Text::from_sections(vec![
                TextSection::new("PRESS \r\n".to_owned(), common_style.clone()),
                TextSection::new(" SPACE \r\n".to_owned(), special_style.clone()),
                TextSection::new("START GAME!\r\n".to_owned(), common_style.clone()),
                TextSection::new(" P \r\n".to_owned(), special_style.clone()),
                TextSection::new("PAUSED GAME!\r\n".to_owned(), common_style.clone()),
            ])
            .with_alignment(align),
            transform: Transform {
                translation: Vec3::new(0., 0., 4.),
                ..Default::default()
            },
            ..Default::default()
        },
        DisplayMenu,
    ));
}

//// 進入游戲顯示系統
fn in_game_display_system(
    mut commands: Commands,
    win_size: Res<WinSize>,
    static_assets: Res<StaticAssets>,
) {
    let font = static_assets.kenney_future_font.clone();
    let common_style = TextStyle {
        font: font.clone(),
        font_size: 32.,
        color: Color::BLUE,
        ..Default::default()
    };
    let special_style = TextStyle {
        font: font.clone(),
        font_size: 38.,
        color: Color::RED,
        ..Default::default()
    };
    let y = -(win_size.height / 2. - GROUND_IMG_SIZE.1 + special_style.font_size * 1.5);
    let align = TextAlignment::Center;
    commands.spawn((
        Text2dBundle {
            text: Text::from_sections(vec![
                TextSection::new("SCORE: ".to_owned(), common_style),
                TextSection::new("0".to_owned(), special_style),
            ])
            .with_alignment(align),
            transform: Transform {
                translation: Vec3::new(0., y, 6.),
                ..Default::default()
            },
            ..Default::default()
        },
        DisplayScore,
    ));
}

/// 進入游戲
fn enter_game_system(kb: Res<Input<KeyCode>>, mut state: ResMut<NextState<GameState>>) {
    if kb.just_released(KeyCode::Space) {
        state.set(GameState::InGame)
    }
}

/// 退出游戲
fn exit_game_system(
    mut commands: Commands,
    query: Query<Entity, (With<Text>, With<DisplayScore>)>,
) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
}
/// 退出選單
fn exit_menu(mut commands: Commands, query: Query<Entity, (With<Text>, With<DisplayMenu>)>) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
}

/// 進入暫停狀態下運行的系統
pub fn enter_paused_system(mut commands: Commands, static_assets: Res<StaticAssets>) {
    // 字體引入
    let font = static_assets.kenney_future_font.clone();
    let common_style = TextStyle {
        font: font.clone(),
        font_size: 32.,
        color: Color::BLUE,
        ..Default::default()
    };
    let special_style = TextStyle {
        font: font.clone(),
        font_size: 38.,
        color: Color::RED,
        ..Default::default()
    };

    let align = TextAlignment::Center;
    commands.spawn((
        Text2dBundle {
            text: Text::from_sections(vec![
                TextSection::new("PAUSED  \r\n".to_owned(), common_style.clone()),
                TextSection::new(" R \r\n".to_owned(), special_style.clone()),
                TextSection::new("RETURN GAME!".to_owned(), common_style.clone()),
            ])
            .with_alignment(align),
            transform: Transform {
                translation: Vec3::new(0., 0., 4.),
                ..Default::default()
            },
            ..Default::default()
        },
        DisplayMenu,
    ));
}

/// 暫停狀態狀態下的鍵盤監聽系統
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<DisplayMenu>)>,
) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
}

/// 游戲中監聽暫停
pub fn in_game_input_system(kb: Res<Input<KeyCode>>, mut next_state: ResMut<NextState<GameState>>) {
    if kb.pressed(KeyCode::P) {
        next_state.set(GameState::Paused);
    }
}

/// 游戲結束狀態下運行的系統
pub fn game_over_enter_system(
    mut commands: Commands,
    game_data: Res<GameData>,
    static_assets: Res<StaticAssets>,
) {
    // 字體引入
    let font = static_assets.kenney_future_font.clone();
    let common_style = TextStyle {
        font: font.clone(),
        font_size: 32.,
        color: Color::BLUE,
        ..Default::default()
    };
    let special_style = TextStyle {
        font: font.clone(),
        font_size: 38.,
        color: Color::RED,
        ..Default::default()
    };

    let align = TextAlignment::Center;
    commands.spawn((
        Text2dBundle {
            text: Text::from_sections(vec![
                TextSection::new(
                    "GAME OVER !  \r\n You got ".to_owned(),
                    common_style.clone(),
                ),
                TextSection::new(game_data.get_score().to_string(), special_style.clone()),
                TextSection::new(" score. \r\n  ".to_owned(), common_style.clone()),
                TextSection::new("SPACE ".to_owned(), special_style.clone()),
                TextSection::new("RESTART GAME! \r\n".to_owned(), common_style.clone()),
                TextSection::new("M ".to_owned(), special_style.clone()),
                TextSection::new("TO MENU".to_owned(), common_style.clone()),
            ])
            .with_alignment(align),
            transform: Transform {
                translation: Vec3::new(0., 80., 4.),
                ..Default::default()
            },
            ..Default::default()
        },
        DisplayGameOver,
    ));
}

/// 退出游戲狀態時執行的系統
pub fn game_over_exit_system(
    mut commands: Commands,
    query: Query<Entity, (With<Text>, With<DisplayGameOver>)>,
    obstacle_query: Query<Entity, With<Obstacle>>,
    player_query: Query<Entity, With<Player>>,
) {
    for entity in query.iter() {
        commands.entity(entity).despawn();
    }
    for entity in obstacle_query.iter() {
        commands.entity(entity).despawn();
    }
    for entity in player_query.iter() {
        commands.entity(entity).despawn();
    }
}

/// 退出游戲狀態監聽
pub fn in_game_over_system(
    kb: Res<Input<KeyCode>>,
    mut game_data: ResMut<GameData>,
    mut next_state: ResMut<NextState<GameState>>,
) {
    game_data.death();
    if kb.pressed(KeyCode::M) {
        next_state.set(GameState::Menu);
    } else if kb.pressed(KeyCode::Space) {
        next_state.set(GameState::InGame);
    }
}

Cargo.toml

[package]
name = "flappy_bird_bevy"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
bevy = { version = "0.10.1" }
rand = "0.8.5"

[workspace]
resolver = "2"

about me

目前失業,在家學習 rust ,

我的 bilibili,我的 Github,

Rust官網
Rust 中文社區

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

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

標籤:其他

上一篇:skywalking自定義插件開發

下一篇:返回列表

標籤雲
其他(157981) Python(38099) JavaScript(25390) Java(17999) C(15217) 區塊鏈(8259) C#(7972) AI(7469) 爪哇(7425) MySQL(7140) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5328) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4559) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2430) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1960) Web開發(1951) HtmlCss(1923) python-3.x(1918) 弹簧靴(1913) C++(1911) xml(1889) PostgreSQL(1873) .NETCore(1855) 谷歌表格(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 專案 使用 bevy 引擎 復刻 Flappy Bird 小游戲

    Rust + Bevy 實作的 Flappy Bird 游戲 簡介 一個使用 bevy 引擎復刻的 Flappy Bird 經典小游戲。 通過該專案我們可以學到:bevy 的自定義組件,自定義插件,自定義資源,sprite 的旋轉,sprite 的移動,sprite sheet 影片的定義使用,狀態 ......

    uj5u.com 2023-04-25 07:46:30 more
  • skywalking自定義插件開發

    skywalking是使用位元組碼操作技術和AOP概念攔截Java類方法的方式來追蹤鏈路的,由于skywalking已經打包了位元組碼操作技術和鏈路追蹤的背景關系傳播,因此只需定義攔截點即可。 這里以skywalking-8.7.0版本為例。 關于插件攔截的原理,可以看我的另一篇文章:skywalking ......

    uj5u.com 2023-04-25 07:46:25 more
  • SpringCloud Gateway 3.x 回應頭添加 Skywalking TraceId

    在微服務架構中,一次請求可能會被多個服務處理,而每個服務又會產生相應的日志,且每個服務也會有多個實體。在這種情況下,如果系統發生例外,沒有 Trace ID,那么在進行日志分析和追蹤時就會非常困難,因為我們無法將所有相關的日志資訊串聯起來。 如果將 Trace ID 添加到回應頭中,那么在進行日志分 ......

    uj5u.com 2023-04-25 07:46:20 more
  • 自定義Python版本ESL庫訪問FreeSWITCH

    環境:CentOS 7.6_x64Python版本:3.9.12FreeSWITCH版本 :1.10.9 一、背景描述 ESL庫是FreeSWITCH對外提供的介面,使用起來很方便,但該庫是基于C語言實作的,Python使用該庫的話需要使用原始碼進行編譯。如果使用系統自帶的Python版本進行編譯,過 ......

    uj5u.com 2023-04-25 07:45:32 more
  • python中的全域變數與區域變數

    1,區域變數與全域變數 1,定義 區域變數:就是在函式體內的變數,在python中冒號“:”后面的變數都是區域變數,當然區域與全域也是一個相對的概念。比如出現函式嵌套的情況。 全域變數:就是在模塊中所有函式都可以呼叫的變數,一般在函式體外被定義。 2,使用程序 函式內的區域變數,在函式體外是不可以使 ......

    uj5u.com 2023-04-25 07:45:23 more
  • Django簡介 安裝下載 app概念 主要目錄介紹

    #目錄 Django簡介 前戲 Django是一個開放源代碼的Web應用框架,由Python寫成。采用了MTV的框架模式,即模型M,視圖V和模版T。這套框架是以比利時的吉普賽爵士吉他手Django Reinhardt來命名的。 一、版本問題 Django1.X: 同步 1.11 Django2.X: ......

    uj5u.com 2023-04-25 07:45:00 more
  • python pyinstaller庫

    簡要 pyinstaller模塊主要用于python代碼打包成exe程式直接使用,這樣在其它電腦上即使沒有python環境也是可以運行的。 用法 一.安裝 pyinstaller屬于第三方庫,因此在使用的時候需提前安裝 pip install pyinstaller 二.配置spec檔案 1.配置生 ......

    uj5u.com 2023-04-25 07:44:41 more
  • python工具模塊介紹-time 時間訪問和轉換

    快速入門 In [1]: import time # 獲取當前時間 In [25]: time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime()) Out[25]: '2018-06-17_20-05-36' # 停頓0.5秒 In [26]: time. ......

    uj5u.com 2023-04-25 07:44:34 more
  • Springboot啟動原理和自動配置原理

    放本地檔案夾都快吃土了,準備清理檔案夾,關于Springboot的! 啟動原理 @SpringBootApplication public class Start { public static void main(String[] args) { SpringApplication.run(Sta ......

    uj5u.com 2023-04-25 07:44:08 more
  • OpenAI ChatGPT 能取代多少程式員的作業?導致失業嗎?

    閱讀原文:https://bysocket.com/openai-chatgpt-vs-developer/ ChatGPT 能取代多少程式員的作業?導致我們程式員失業嗎?這是一個很好的話題,我這里分享下: 一、ChatGPT 是什么?有什么作用 ChatGPT是一種基于人工智能技術的語言模型,是可 ......

    uj5u.com 2023-04-25 07:44:01 more