use bevy::{prelude::*, render::camera::Viewport, window::WindowResized};
#[derive(Component)]
pub struct LeftCamera;
#[derive(Component)]
pub struct RightCamera;
#[derive(Default)]
pub struct SplitScreenPlugin;
impl Plugin for SplitScreenPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, set_camera_viewports_for_split_screen);
}
}
fn set_camera_viewports_for_split_screen(
windows: Query<&Window>,
mut resize_events: EventReader<WindowResized>,
mut left_camera: Query<&mut Camera, (With<LeftCamera>, Without<RightCamera>)>,
mut right_camera: Query<&mut Camera, With<RightCamera>>,
) {
for resize_event in resize_events.read() {
let window = windows.get(resize_event.window).unwrap();
if let (Ok(mut left_camera), Ok(mut right_camera)) =
(left_camera.get_single_mut(), right_camera.get_single_mut())
{
left_camera.viewport = Some(Viewport {
physical_position: UVec2::new(0, 0),
physical_size: UVec2::new(
window.resolution.physical_width() / 2,
window.resolution.physical_height(),
),
..default()
});
left_camera.order = 1;
right_camera.viewport = Some(Viewport {
physical_position: UVec2::new(window.resolution.physical_width() / 2, 0),
physical_size: UVec2::new(
window.resolution.physical_width() / 2,
window.resolution.physical_height(),
),
..default()
});
right_camera.order = 2;
}
}
}