Skip to content

Commit 6b4795c

Browse files
committed
Add Camera::viewport_to_world_2d (#6557)
# Objective Add a simpler and less expensive 2D variant of `viewport_to_world`. Co-authored-by: devil-ira <[email protected]>
1 parent 39e14a4 commit 6b4795c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

crates/bevy_render/src/camera/camera.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,25 @@ impl Camera {
248248
})
249249
}
250250

251+
/// Returns a 2D world position computed from a position on this [`Camera`]'s viewport.
252+
///
253+
/// Useful for 2D cameras and other cameras with an orthographic projection pointing along the Z axis.
254+
///
255+
/// To get the world space coordinates with Normalized Device Coordinates, you should use
256+
/// [`ndc_to_world`](Self::ndc_to_world).
257+
pub fn viewport_to_world_2d(
258+
&self,
259+
camera_transform: &GlobalTransform,
260+
viewport_position: Vec2,
261+
) -> Option<Vec2> {
262+
let target_size = self.logical_viewport_size()?;
263+
let ndc = viewport_position * 2. / target_size - Vec2::ONE;
264+
265+
let world_near_plane = self.ndc_to_world(camera_transform, ndc.extend(1.))?;
266+
267+
Some(world_near_plane.truncate())
268+
}
269+
251270
/// Given a position in world space, use the camera's viewport to compute the Normalized Device Coordinates.
252271
///
253272
/// When the position is within the viewport the values returned will be between -1.0 and 1.0 on the X and Y axes,

0 commit comments

Comments
 (0)