use bevy::{prelude::*, window::WindowResized};
fn main() {
App::new()
.insert_resource(ResolutionSettings {
large: Vec2::new(1920.0, 1080.0),
medium: Vec2::new(800.0, 600.0),
small: Vec2::new(640.0, 360.0),
})
.add_plugins(DefaultPlugins)
.add_systems(Startup, (setup_camera, setup_ui))
.add_systems(Update, (on_resize_system, toggle_resolution))
.run();
}
#[derive(Component)]
struct ResolutionText;
#[derive(Resource)]
struct ResolutionSettings {
large: Vec2,
medium: Vec2,
small: Vec2,
}
fn setup_camera(mut commands: Commands) {
commands.spawn(Camera2d);
}
fn setup_ui(mut commands: Commands) {
commands
.spawn(Node {
width: Val::Percent(100.),
..default()
})
.with_child((
Text::new("Resolution"),
TextFont {
font_size: 42.0,
..default()
},
ResolutionText,
));
}
fn toggle_resolution(
keys: Res<ButtonInput<KeyCode>>,
mut window: Single<&mut Window>,
resolution: Res<ResolutionSettings>,
) {
if keys.just_pressed(KeyCode::Digit1) {
let res = resolution.small;
window.resolution.set(res.x, res.y);
}
if keys.just_pressed(KeyCode::Digit2) {
let res = resolution.medium;
window.resolution.set(res.x, res.y);
}
if keys.just_pressed(KeyCode::Digit3) {
let res = resolution.large;
window.resolution.set(res.x, res.y);
}
}
fn on_resize_system(
mut text: Single<&mut Text, With<ResolutionText>>,
mut resize_reader: EventReader<WindowResized>,
) {
for e in resize_reader.read() {
text.0 = format!("{:.1} x {:.1}", e.width, e.height);
}
}