From cb64a4aa8ad6cc0d6398ca46507320c2d54639b2 Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 10 Jul 2025 04:37:56 +0200 Subject: [PATCH] Refactor `3d_viewport_to_world` example with let chains (#20071) # Objective Make use of let chains to reduce LoC where we previously used let else to cut down on indentation. Best of both worlds. --- examples/3d/3d_viewport_to_world.rs | 49 +++++++++++------------------ 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/examples/3d/3d_viewport_to_world.rs b/examples/3d/3d_viewport_to_world.rs index 9aabd6f629..883121779a 100644 --- a/examples/3d/3d_viewport_to_world.rs +++ b/examples/3d/3d_viewport_to_world.rs @@ -13,41 +13,30 @@ fn main() { fn draw_cursor( camera_query: Single<(&Camera, &GlobalTransform)>, ground: Single<&GlobalTransform, With>, - 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) + // 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())) + { + let point = ray.get_point(distance); - // 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) = - 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. - gizmos.circle( - Isometry3d::new( - point + ground.up() * 0.01, - Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()), - ), - 0.2, - Color::WHITE, - ); + // Draw a circle just above the ground plane at that position. + gizmos.circle( + Isometry3d::new( + point + ground.up() * 0.01, + Quat::from_rotation_arc(Vec3::Z, ground.up().as_vec3()), + ), + 0.2, + Color::WHITE, + ); + } } #[derive(Component)]