diff --git a/src/primitives.rs b/src/primitives.rs index 462f433..4aa1273 100644 --- a/src/primitives.rs +++ b/src/primitives.rs @@ -242,23 +242,10 @@ pub mod rays { camera: &Camera, camera_transform: &GlobalTransform, ) -> Option { - let view = camera_transform.compute_matrix(); - - let (viewport_min, viewport_max) = camera.logical_viewport_rect()?; - let screen_size = camera.logical_target_size()?; - let viewport_size = viewport_max - viewport_min; - let adj_cursor_pos = - cursor_pos_screen - Vec2::new(viewport_min.x, screen_size.y - viewport_max.y); - - let projection = camera.projection_matrix(); - let far_ndc = projection.project_point3(Vec3::NEG_Z).z; - let near_ndc = projection.project_point3(Vec3::Z).z; - let cursor_ndc = (adj_cursor_pos / viewport_size) * 2.0 - Vec2::ONE; - let ndc_to_world: Mat4 = view * projection.inverse(); - let near = ndc_to_world.project_point3(cursor_ndc.extend(near_ndc)); - let far = ndc_to_world.project_point3(cursor_ndc.extend(far_ndc)); - let ray_direction = far - near; - Some(Ray3d::new(near, ray_direction)) + match camera.viewport_to_world(camera_transform, cursor_pos_screen) { + Some(r) => Some(Ray3d::new(r.origin, r.direction)), + None => None, + } } /// Checks if the ray intersects with an AABB of a mesh.