Skip to content

Commit 35b9a21

Browse files
authored
Add a translate method to Rect (#24139)
# Objective Add a `translate` method to `Rect`. ## Solution Add a `translate` method to `Rect`. ## Testing Added a `rect_translate` test to the `rect` module.
1 parent 152dc2f commit 35b9a21

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

crates/bevy_math/src/rects/rect.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,25 @@ impl Rect {
215215
)
216216
}
217217

218+
/// Returns the rectangle translated by the given offset.
219+
///
220+
/// # Examples
221+
///
222+
/// ```
223+
/// # use bevy_math::{Rect, Vec2};
224+
/// let r = Rect::new(0., 0., 5., 1.); // w=5 h=1
225+
/// let r2 = r.translate(Vec2::new(2., -3.));
226+
/// assert!(r2.min.abs_diff_eq(Vec2::new(2., -3.), 1e-5));
227+
/// assert!(r2.max.abs_diff_eq(Vec2::new(7., -2.), 1e-5));
228+
/// ```
229+
#[inline]
230+
pub const fn translate(&self, offset: Vec2) -> Self {
231+
Self {
232+
min: Vec2::new(self.min.x + offset.x, self.min.y + offset.y),
233+
max: Vec2::new(self.max.x + offset.x, self.max.y + offset.y),
234+
}
235+
}
236+
218237
/// Check if a point lies within this rectangle, inclusive of its edges.
219238
///
220239
/// # Examples
@@ -535,4 +554,14 @@ mod tests {
535554
assert!(r2.min.abs_diff_eq(Vec2::new(-0.8, -0.8), 1e-5));
536555
assert!(r2.max.abs_diff_eq(Vec2::new(0.8, 0.8), 1e-5));
537556
}
557+
558+
#[test]
559+
fn rect_translate() {
560+
let r = Rect::new(0., 1., 4., 3.);
561+
let r2 = r.translate(Vec2::new(2., -5.));
562+
563+
assert!(r2.min.abs_diff_eq(Vec2::new(2., -4.), 1e-5));
564+
assert!(r2.max.abs_diff_eq(Vec2::new(6., -2.), 1e-5));
565+
assert!(r2.size().abs_diff_eq(r.size(), 1e-5));
566+
}
538567
}

0 commit comments

Comments
 (0)