如何使用 Camera2dComponents 在 Bevy 中将屏幕空间转换为世界空间坐标?

Jak*_*old 6 rust bevy

使用Res<Events<CursorMoved>>I 可以获得屏幕空间坐标中的鼠标位置变化(左下角为零),例如

#[derive(Default)]
struct State {
    cursor_moved_reader: EventReader<CursorMoved>,
}

fn set_mouse_pos(mut state: ResMut<State>, cursor_moved: Res<Events<CursorMoved>>) {
    for event in state.cursor_moved_reader.iter(&cursor_moved) {
        println!("cursor: {:?}", event.position);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,当使用来自sprite的相机时,我是否将SpriteComponents'设置transform.translation为光标位置,Camera2dComponents::default()并且位置0, 0呈现在屏幕的中心。在屏幕空间鼠标坐标和相机世界空间坐标之间转换的惯用方法是什么?

the*_*dry 0

当我第一次开始使用bevy. 这是我目前用来从窗口转换到世界坐标的方法(对于 2D 游戏):

fn window_to_world(
    window: &Window,
    camera: &Transform,
    position: &Vec2,
) -> Vec3 {
    let center = camera.translation.truncate();
    let half_width = (window.width() / 2.0) * camera.scale.x;
    let half_height = (window.height() / 2.0) * camera.scale.y;
    let left = center.x - half_width;
    let bottom = center.y - half_height;
    Vec3::new(
        left + position.x * camera.scale.x,
        bottom + position.y * camera.scale.y,
        0.0,  // I'm working in 2D
    )
}
Run Code Online (Sandbox Code Playgroud)

在 中bevyWindow坐标系的原点(0, 0)位于左下角以像素为单位测量,并随着屏幕向上移动而增加。Camera坐标默认位于(0, 0)窗口的中心,以对您的游戏最有意义的单位进行测量。

此功能受到限制,因为它不考虑相机的旋转,仅考虑比例。