Skip to content

Commit

Permalink
Fixes camera boundary checks
Browse files Browse the repository at this point in the history
  • Loading branch information
mnmaita committed Nov 15, 2023
1 parent 3e57761 commit 46feec5
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions src/camera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,29 +39,46 @@ fn update_camera(

fn constrain_camera_position_to_level(
mut camera_query: Query<(&Camera, &mut Transform), With<Camera2d>>,
#[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);
}
}
}

0 comments on commit 46feec5

Please sign in to comment.