Skip to content

Commit

Permalink
normalize method for Rect (#10297)
Browse files Browse the repository at this point in the history
# Objective

`normalize` method that expresses a rectangle relative to a normalized
[0..1] x [0..1] space defined by another rectangle.

Useful for UI and texture atlas calculations etc.

---------

Co-authored-by: Rob Parrett <robparrett@gmail.com>
  • Loading branch information
ickshonpe and rparrett committed Oct 28, 2023
1 parent 0824812 commit c959c1b
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions crates/bevy_math/src/rects/rect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,30 @@ impl Rect {
r
}

/// Build a new rectangle from this one with its coordinates expressed
/// relative to `other` in a normalized ([0..1] x [0..1]) coordinate system.
///
/// # Examples
///
/// ```rust
/// # use bevy_math::{Rect, Vec2};
/// let r = Rect::new(2., 3., 4., 6.);
/// let s = Rect::new(0., 0., 10., 10.);
/// let n = r.normalize(s);
///
/// assert_eq!(n.min.x, 0.2);
/// assert_eq!(n.min.y, 0.3);
/// assert_eq!(n.max.x, 0.4);
/// assert_eq!(n.max.y, 0.6);
/// ```
pub fn normalize(&self, other: Self) -> Self {
let outer_size = other.size();
Self {
min: (self.min - other.min) / outer_size,
max: (self.max - other.min) / outer_size,
}
}

/// Returns self as [`IRect`] (i32)
#[inline]
pub fn as_irect(&self) -> IRect {
Expand Down

0 comments on commit c959c1b

Please sign in to comment.