diff --git a/src/debug.rs b/src/debug.rs new file mode 100644 index 0000000..11e0b8f --- /dev/null +++ b/src/debug.rs @@ -0,0 +1,113 @@ +use bevy::prelude::*; + +use crate::{camera::MainCamera, player::Player}; + +#[derive(Component)] +pub struct DebugCamera; + +fn spawn_debug_camera(mut commands: Commands) { + commands.spawn(( + DebugCamera, + Camera2d, + Camera { + is_active: false, + ..default() + }, + )); +} + +fn setup_debug_camera(mut camera: Single<&mut Projection, With>) { + if let Projection::Orthographic(ref mut projection) = **camera { + projection.scale = 4.0; + } +} + +fn toggle_debug_camera( + input: Res>, + mut main_camera: Single<&mut Camera, (With, Without)>, + mut debug_camera: Single<&mut Camera, (With, Without)>, +) { + if input.just_pressed(KeyCode::Tab) { + main_camera.is_active = !main_camera.is_active; + debug_camera.is_active = !debug_camera.is_active; + } +} + +fn follow_player_debug( + player: Single<&Transform, (With, Without)>, + mut debug_camera: Single<&mut Transform, (With, Without)>, +) { + debug_camera.translation.y = player.translation.y; +} + +enum FrameSide { + Top, + Bottom, + Left, + Right, +} + +#[derive(Component)] +struct FramePart(FrameSide); + +fn spawn_debug_frame(mut commands: Commands) { + for side in [ + FrameSide::Top, + FrameSide::Bottom, + FrameSide::Left, + FrameSide::Right, + ] { + let size = match side { + FrameSide::Top | FrameSide::Bottom => Vec2::new(1936.0, 8.0), + FrameSide::Left | FrameSide::Right => Vec2::new(8.0, 1096.0), + }; + + commands.spawn(( + FramePart(side), + Sprite::from_color(Color::srgb(1.0, 0.0, 0.0), size), + Visibility::Hidden, + )); + } +} + +fn draw_view_frame( + main_camera: Single<&Transform, (With, Without)>, + debug_camera: Single<&Camera, (With, Without)>, + mut frame: Query< + (&FramePart, &mut Transform, &mut Visibility), + (Without, Without), + >, +) { + let center = main_camera.translation; + let half_width = 960.0; + let half_height = 540.0; + + let visible = if debug_camera.is_active { + Visibility::Visible + } else { + Visibility::Hidden + }; + + for (frame_part, mut frame_transform, mut visibility) in &mut frame { + let position = match frame_part.0 { + FrameSide::Top => Vec3::new(center.x, center.y + half_height, 10.0), + FrameSide::Bottom => Vec3::new(center.x, center.y - half_height, 10.0), + FrameSide::Left => Vec3::new(center.x - half_width, center.y, 10.0), + FrameSide::Right => Vec3::new(center.x + half_width, center.y, 10.0), + }; + frame_transform.translation = position; + *visibility = visible; + } +} +pub struct DebugPlugin; + +impl Plugin for DebugPlugin { + fn build(&self, app: &mut App) { + app.add_systems(Startup, spawn_debug_camera) + .add_systems(Startup, setup_debug_camera.after(spawn_debug_camera)) + .add_systems(Startup, spawn_debug_frame) + .add_systems(Update, draw_view_frame) + .add_systems(Update, follow_player_debug) + .add_systems(Update, toggle_debug_camera); + } +}