From 46feec50bae25253ef79986fc4d73d9cd51ec0c8 Mon Sep 17 00:00:00 2001 From: mnmaita <47983254+mnmaita@users.noreply.github.com> Date: Wed, 15 Nov 2023 01:47:31 +0100 Subject: [PATCH] Fixes camera boundary checks --- src/camera.rs | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/src/camera.rs b/src/camera.rs index 5012e6c..25e839e 100644 --- a/src/camera.rs +++ b/src/camera.rs @@ -39,29 +39,46 @@ fn update_camera( fn constrain_camera_position_to_level( mut camera_query: Query<(&Camera, &mut Transform), With>, + #[cfg(debug_assertions)] mut gizmos: Gizmos, ) { let (camera, mut camera_transform) = camera_query.single_mut(); if let Some(viewport_size) = camera.logical_viewport_size() { let level_dimensions = GRID_SIZE * TILE_SIZE; - let half_viewport_size = viewport_size * 0.5; + let viewport_size_remainder = viewport_size % TILE_SIZE; + let camera_boundary_size = (level_dimensions + - (viewport_size - viewport_size_remainder) + - viewport_size_remainder) + .clamp(Vec2::ZERO, Vec2::splat(f32::MAX)); + let camera_boundary = Rect::from_center_size(-HALF_TILE_SIZE, camera_boundary_size); - camera_transform.translation.x = if viewport_size.x > level_dimensions.x { - 0.0 - } else { - let level_half_width = level_dimensions.x * 0.5; - let min = -level_half_width + half_viewport_size.x + HALF_TILE_SIZE.x; - let max = level_half_width - half_viewport_size.x - HALF_TILE_SIZE.x; - camera_transform.translation.x.clamp(min, max) - }; + if camera_boundary.is_empty() { + if viewport_size.x > level_dimensions.x { + camera_transform.translation.x = 0.0; + } + if viewport_size.y > level_dimensions.y { + camera_transform.translation.y = 0.0; + } + } - camera_transform.translation.y = if viewport_size.y > level_dimensions.y { - 0.0 - } else { - let level_half_height = level_dimensions.y * 0.5; - let min = -level_half_height + half_viewport_size.y + HALF_TILE_SIZE.y; - let max = level_half_height - half_viewport_size.y - HALF_TILE_SIZE.y; - camera_transform.translation.y.clamp(min, max) - }; + if camera_boundary.size() != Vec2::ZERO + && !camera_boundary.contains(camera_transform.translation.truncate()) + { + let (min_x, max_x) = (camera_boundary.min.x, camera_boundary.max.x); + let (min_y, max_y) = (camera_boundary.min.y, camera_boundary.max.y); + camera_transform.translation.x = camera_transform.translation.x.clamp(min_x, max_x); + camera_transform.translation.y = camera_transform.translation.y.clamp(min_y, max_y); + } + + #[cfg(debug_assertions)] + { + gizmos.rect_2d( + camera_boundary.center(), + 0., + camera_boundary.size(), + Color::RED, + ); + gizmos.circle_2d(camera_transform.translation.truncate(), 10., Color::RED); + } } }