#bevy #assets #gamedev

bevy_asset_manager

在bevy中实现简单的资源加载和组织

1个不稳定版本

0.1.0 2023年11月26日

#2210 in 游戏开发

MIT许可证

17KB
156 代码行

Bevy资源管理器

这个crate为Bevy游戏引擎提供了一种简单的资源管理系统。它定义了一个AssetManager,用于根据枚举键变体加载和检索资源,支持懒加载和急切加载游戏资源。提供了宏以便于创建资源管理器。

示例

use bevy::prelude::{Commands, Component, Res, Resource, States};
use bevy_asset_manager::{mixed_asset_manager, AssetManager};
use bevy_kira_audio::{AudioApp, AudioChannel, AudioControl, AudioSource};

pub struct ShipPlugin;

impl Plugin for ShipPlugin {
    fn build(&self, app: &mut bevy::prelude::App) {
        app.add_audio_channel::<Ship>()
            .add_state::<ShipState>()
            .add_systems(Startup, setup)
            .add_systems(Update, handle_input)
            .add_systems(OnEnter(ShipState::Idle), idle)
            .add_systems(OnEnter(ShipState::Accelerate), accelerate);
    }
}

#[derive(Component, Resource)]
struct Ship;

#[derive(States, Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
enum ShipState {
    #[default]
    Idle,
    Accelerate,
}

// Shorthand for our ship audio's asset manager
type ShipAudioManager = AssetManager<ShipAudio, AudioSource>;

// Keys for our ship audio
enum ShipAudio {
    EngineOn,
    EngineOff,
    Warp,
}

// Create an asset manager resource and insert it into our runtime
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.insert_resource(
        mixed_asset_manager!(<ShipAudio, AudioSource> binds asset_server.clone(), {
            LoadStyle::Loaded, ShipAudio::EngineOn => "sounds/engine-on.ogg",
            LoadStyle::Loaded, ShipAudio::EngineOff => "sounds/engine-off.ogg",
            LoadStyle::Lazy, ShipAudio::Warp => "sounds/warp.ogg",
        }),
    );
}

// Retrieve and use our engine on audio asset
fn accelerate(hannel: Res<AudioChannel<Ship>>, audio_manager: Res<ShipAudioManager>) {
    audio.stop();
    audio
        .play(audio_manager.get(ShipAudio::EngineOn).unwrap())
        .with_volume(0.5)
        .loop_from(1.0);
}

// Retrieve and use our engine off audio asset
fn idle(hannel: Res<AudioChannel<Ship>>, audio_manager: Res<ShipAudioManager>) {
    audio.stop();
    audio
        .play(audio_manager.get(ShipAudio::EngineOff).unwrap())
        .with_volume(0.5);
}

fn handle_input(keys: Res<Input<KeyCode>>, mut ship_state: ResMut<NextState<ShipState>>) {
    if keys.just_pressed(KeyCode::W) {
        ship_state.set(ShipState::Accelerate);
    }

    if keys.just_released(KeyCode::W) {
        ship_state.set(ShipState::Idle);
    }
}

注意

本文档假设您熟悉Bevy的资源API和ECS框架。请确保Bevy已正确集成到您的项目中,以便最佳使用此crate。

有关Bevy资源的更多详细信息,请参阅Bevy文档:Bevy文档

依赖项

~22–54MB
~884K SLoC