Skip to content

Commit

Permalink
Add Camera::viewport_to_world_2d (bevyengine#6557)
Browse files Browse the repository at this point in the history
# Objective

Add a simpler and less expensive 2D variant of `viewport_to_world`.

Co-authored-by: devil-ira <justthecooldude@gmail.com>
  • Loading branch information
2 people authored and alradish committed Jan 22, 2023
1 parent 58ae86d commit 1fa9168
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions crates/bevy_render/src/camera/camera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,25 @@ impl Camera {
})
}

/// Returns a 2D world position computed from a position on this [`Camera`]'s viewport.
///
/// Useful for 2D cameras and other cameras with an orthographic projection pointing along the Z axis.
///
/// To get the world space coordinates with Normalized Device Coordinates, you should use
/// [`ndc_to_world`](Self::ndc_to_world).
pub fn viewport_to_world_2d(
&self,
camera_transform: &GlobalTransform,
viewport_position: Vec2,
) -> Option<Vec2> {
let target_size = self.logical_viewport_size()?;
let ndc = viewport_position * 2. / target_size - Vec2::ONE;

let world_near_plane = self.ndc_to_world(camera_transform, ndc.extend(1.))?;

Some(world_near_plane.truncate())
}

/// Given a position in world space, use the camera's viewport to compute the Normalized Device Coordinates.
///
/// When the position is within the viewport the values returned will be between -1.0 and 1.0 on the X and Y axes,
Expand Down

0 comments on commit 1fa9168

Please sign in to comment.