0

我对 Bevy 和 Rust 还很陌生。我想加载一个 png 图像并获取它的宽度和高度。下面的代码不会打印“找到的资源...”。

fn setup( mut commands: Commands,
      asset_server: Res<AssetServer>,
      mut materials: ResMut<Assets<Image>>) {
let texture_handle = asset_server.load("board.png");

//materials.add(texture_handle.clone().into()); //Gives error: the trait `From<Handle<_>>` is not implemented for `bevy::prelude::Image`

commands.spawn().insert_bundle(SpriteBundle {
    texture: texture_handle.clone(),
    ..Default::default()
}).insert(BackgroundSprite);

if let Some(image) = materials.get(texture_handle) {
    print!("found resource with width and height: [{},{}]", image.texture_descriptor.size.width, image.texture_descriptor.size.height);
}

}

4

1 回答 1

0

在 Bevy Discord 帮助频道获得一些帮助后,我想通了。

资源是异步加载的,必须在以后访问。在此处查看 AssetEvent 示例

我是 Rust 的初学者,所以我不会说这是这样做的方法。但这是我的结果:

#[derive(Component)]
pub struct BackgroundHandle {
    handle: Handle<Image>,
}

#[derive(Component)]
pub struct BackgroundSpriteSize {
    width: u32,
    height: u32,
}

fn setup( mut commands: Commands,
          mut app_state: ResMut<State<BoardState>>,
          asset_server: Res<AssetServer>) {
    let texture_handle = asset_server.load("board.png");

    commands.spawn().insert_bundle(SpriteBundle {
        texture: texture_handle.clone(),
        ..Default::default()
    }).insert(BackgroundSpriteBundle);

    commands.insert_resource(BackgroundHandle {
        handle: texture_handle,
    });

    app_state.set(BoardState::Initializing);
}

fn setupBounds(mut commands: Commands,
               mut app_state: ResMut<State<BoardState>>,
               mut ev_asset: EventReader<AssetEvent<Image>>,
               assets: Res<Assets<Image>>,
               bg: Res<BackgroundHandle>) {

    for ev in ev_asset.iter() {
        match ev {
            AssetEvent::Created { handle } => {
                if *handle == bg.handle {
                    let img = assets.get(bg.handle.clone()).unwrap();

                    let bg_size = BackgroundSpriteSize {
                        width: img.texture_descriptor.size.width,
                        height: img.texture_descriptor.size.height,
                    };

                    commands.insert_resource(bg_size);
                    app_state.set(BoardState::Initialized);
                }
            },
            _ => {

            }
        }
    }
}
于 2022-01-11T09:51:05.947 回答