1

如何为我的 2d 游戏添加背景图像?代码在这里:

https://github.com/mthelm85/game

assets/textures我有一个名为的文件pitch.png中,我想将其用作窗口的背景。我找不到有关如何执行此操作的任何信息。

谢谢!

4

1 回答 1

2

您不需要设置z-translation. Bevy 会将最后添加的项目呈现在顶部。因此,如果您想将图像用作背景,只需先生成相应的精灵,如下所示:

fn setup(
    commands: &mut Commands,
    asset_server: Res<AssetServer>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    let background_image: Handle<Texture> = asset_server.load("textures/pitch.png");
    let texture_handle = asset_server.load("sprites/sprite_max.png");
    commands
        .spawn(Camera2dBundle::default())
        .spawn(SpriteBundle {
            material: materials.add(background_image.into()),
            ..Default::default()
        })
        .spawn(SpriteBundle {
            material: materials.add(texture_handle.into()),
            ..Default::default()
        })
        .with(Max);
}

如果您希望图像最初覆盖整个屏幕,则必须相应地对其进行缩放,例如:

use bevy::prelude::*;

fn main() {
    App::build()
        .add_resource(WindowDescriptor {
            title: "Game".to_string(),
            width: 900.0,
            height: 900.0,
            vsync: true,
            resizable: false,
            ..Default::default()
        })
        .add_system(move_max.system())
        .add_plugins(DefaultPlugins)
        .add_startup_system(setup.system())
        .run();
}

fn setup(
    commands: &mut Commands,
    asset_server: Res<AssetServer>,
    mut materials: ResMut<Assets<ColorMaterial>>,
) {
    let background_image: Handle<Texture> = asset_server.load("textures/pitch.png");
    let texture_handle = asset_server.load("sprites/sprite_max.png");
    commands
        .spawn(Camera2dBundle::default())
        .spawn(SpriteBundle {
            material: materials.add(background_image.into()),
            transform: Transform::from_scale(Vec3::new(1.5, 1.5, 0.0)),
            ..Default::default()
        })
        .spawn(SpriteBundle {
            material: materials.add(texture_handle.into()),
            ..Default::default()
        })
        .with(Max);
}

struct Max;

fn move_max(
    keyboard_input: Res<Input<KeyCode>>,
    mut max_positions: Query<&mut Transform, With<Max>>,
) {
    for mut transform in max_positions.iter_mut() {
        if keyboard_input.pressed(KeyCode::Left) {
            transform.translation.x -= 1.0;
        }
        if keyboard_input.pressed(KeyCode::Right) {
            transform.translation.x += 1.0;
        }
        if keyboard_input.pressed(KeyCode::Down) {
            transform.translation.y -= 1.0;
        }
        if keyboard_input.pressed(KeyCode::Up) {
            transform.translation.y += 1.0;
        }
    }
}
于 2021-02-16T10:06:54.680 回答