@@ -144,6 +144,16 @@ impl<T> Rect<T> where T: Add<Output = T> + Ord + Copy {
144144 pos. x >= self . origin . x && pos. x < self . origin . x + self . width ( )
145145 && pos. y >= self . origin . y && pos. y < self . origin . y + self . height ( )
146146 }
147+
148+ /// Checks whether the rectangle intersects the given rectangle.
149+ pub fn intersects ( self , other : Rect < T > ) -> bool {
150+ let s1 = self . top_left ( ) ;
151+ let e1 = self . bottom_right ( ) ;
152+ let s2 = other. top_left ( ) ;
153+ let e2 = other. bottom_right ( ) ;
154+ s2. x < e1. x && s1. x < e2. x &&
155+ s2. y < e1. y && s1. y < e2. y
156+ }
147157}
148158
149159impl < T > Rect < T > where T : Add < Output = T > + Sub < Output = T > + TryInto < usize > + Ord + Copy , T :: Error : Debug {
@@ -157,6 +167,8 @@ impl<T> Rect<T> where T: Add<Output = T> + Sub<Output = T> + TryInto<usize> + Or
157167
158168#[ cfg( test) ]
159169mod tests {
170+ use std:: ops:: Sub ;
171+
160172 use crate :: Vec2 ;
161173
162174 use super :: Rect ;
@@ -176,4 +188,18 @@ mod tests {
176188 assert_eq ! ( rect. bottom_center( ) , Vec2 :: new( 0 , 1 ) ) ;
177189 assert_eq ! ( rect. bottom_right( ) , Vec2 :: new( 1 , 1 ) ) ;
178190 }
191+
192+ #[ test]
193+ fn intersections ( ) {
194+ assert ! ( rect( 0 , 0 , 2 , 2 ) . intersects( rect( 1 , 1 , 3 , 3 ) ) ) ;
195+ assert ! ( rect( 0 , 0 , 2 , 2 ) . intersects( rect( 1 , -1 , 1 , 3 ) ) ) ;
196+ assert ! ( !rect( 0 , -2 , 1 , 1 ) . intersects( rect( 1 , -1 , 1 , 3 ) ) ) ;
197+ assert ! ( !rect( 0 , 0 , 1 , 1 ) . intersects( rect( 1 , 0 , 2 , 1 ) ) ) ;
198+ assert ! ( rect( 0 , 0 , 2 , 1 ) . intersects( rect( 1 , 0 , 2 , 1 ) ) ) ;
199+ assert ! ( !rect( 0 , 0 , 2 , 0 ) . intersects( rect( 1 , 0 , 2 , 1 ) ) ) ;
200+ }
201+
202+ fn rect < T > ( sx : T , sy : T , ex : T , ey : T ) -> Rect < T > where T : Copy + Sub < Output = T > {
203+ Rect :: new ( Vec2 :: new ( sx, sy) , Vec2 :: new ( ex - sx, ey - sy) )
204+ }
179205}
0 commit comments