How, with Bevy, can you get and set Window information after creation?
Asked Answered
Y

3

13

I want to be able to read and set window-settings with Bevy. I attempted to do so with a basic system:

fn test_system(mut win_desc: ResMut<WindowDescriptor>) {
    win_desc.title = "test".to_string();
    println!("{}",win_desc.title);
}

While this works (partially), it only gives you the original settings, and it doesn't allow changes at all. In this example, the title will not change, but the display of the title will. In another example, changing the window-size (manually at run-time) will not be reflected if you were to print win_desc.width.

Yerkovich answered 29/8, 2020 at 23:43 Comment(0)
A
12

At the moment, the WindowDescriptor is used only during window creation and is not updated later

To get notified when the window is resized I use this system:

fn resize_notificator(resize_event: Res<Events<WindowResized>>) {
    let mut reader = resize_event.get_reader();
    for e in reader.iter(&resize_event) {
        println!("width = {} height = {}", e.width, e.height);
    }
}

Other useful events can be found at https://github.com/bevyengine/bevy/blob/master/crates/bevy_window/src/event.rs

Arzola answered 31/8, 2020 at 7:7 Comment(2)
Does this mean that currently we cannot resize the window?Yerkovich
upvoted; this was helpful, but I think it's out-of-date; the current way to access window resize events seems to be to have a system function parameter of mut resize_events: EventReader<WindowResized>, and then inside the system function do for event in resize_events.read().into_iter() {...}Fibrinous
H
8

With Bevy 0.10 you can do this:

fn get_window(window: Query<&Window>) {
    let window = window.single();

    let width = window.resolution.width();
    let height = window.resolution.height();

    let (x, y) = match window.position {
        WindowPosition::At(v) => (v.x as f32, v.y as f32),
        _ => (0., 0.),
    };

    dbg!(width, height, x, y);
}
Helluva answered 8/7, 2023 at 16:13 Comment(1)
this was helpful; I will note that window.width() and window.height() are available, and they return the same info as the window.resolution. ... functionsFibrinous
H
6

There's a nice example of working with windows provided in the bevy GitHub repo: https://github.com/bevyengine/bevy/blob/master/examples/window/window_settings.rs

For your case of reading / writing window size:

fn window_resize_system(mut windows: ResMut<Windows>) {
    let window = windows.get_primary_mut().unwrap();
    println!("Window size was: {},{}", window.width(), window.height());
    window.set_resolution(1280, 720);
}

As zyrg mentioned, you can also listen for window events.

Hans answered 7/12, 2020 at 3:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.