Refactor 3d_viewport_to_world example with let chains

This commit is contained in:
Tim Blackbird 2025-07-10 01:19:23 +02:00
parent 6f6d8312f3
commit 60fc739b74

View File

@ -13,30 +13,18 @@ fn main() {
fn draw_cursor(
camera_query: Single<(&Camera, &GlobalTransform)>,
ground: Single<&GlobalTransform, With<Ground>>,
windows: Query<&Window>,
window: Single<&Window>,
mut gizmos: Gizmos,
) {
let Ok(windows) = windows.single() else {
return;
};
let (camera, camera_transform) = *camera_query;
let Some(cursor_position) = windows.cursor_position() else {
return;
};
if let Some(cursor_position) = window.cursor_position()
// Calculate a ray pointing from the camera into the world based on the cursor's position.
let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position) else {
return;
};
// Calculate if and where the ray is hitting the ground plane.
let Some(distance) =
&& let Ok(ray) = camera.viewport_to_world(camera_transform, cursor_position)
// Calculate if and at what distance the ray is hitting the ground plane.
&& let Some(distance) =
ray.intersect_plane(ground.translation(), InfinitePlane3d::new(ground.up()))
else {
return;
};
{
let point = ray.get_point(distance);
// Draw a circle just above the ground plane at that position.
@ -49,6 +37,7 @@ fn draw_cursor(
Color::WHITE,
);
}
}
#[derive(Component)]
struct Ground;