Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Add Camera::viewport_to_world_2d #6557

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it worth leaving stronger language? IIUC, the results are only correct when the projection is orthographic.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should say something like

A more efficient version of [viewport_to_world] that only works for cameras with an orthographic projection, such as 2D cameras.

///
/// 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