1 use super::vector2::Vector2; 2 3 /// 表示一个矩形区域 4 #[derive(Clone, Copy, Debug, Default)] 5 pub struct Rect { 6 /// 左上角x坐标(世界坐标) 7 pub x: i32, 8 /// 左上角y坐标(世界坐标) 9 pub y: i32, 10 /// 矩形宽度 11 pub width: u32, 12 /// 矩形高度 13 pub height: u32, 14 } 15 16 impl Rect { new(x: i32, y: i32, width: u32, height: u32) -> Rect17 pub fn new(x: i32, y: i32, width: u32, height: u32) -> Rect { 18 Rect { 19 x: x, 20 y: y, 21 width: width, 22 height: height, 23 } 24 } 25 26 /// 返回矩形左上角的位置点 top_left_pos(&self) -> Vector227 pub fn top_left_pos(&self) -> Vector2 { 28 Vector2::new(self.x, self.y) 29 } 30 top_pos(&self) -> Vector231 pub fn top_pos(&self) -> Vector2 { 32 Vector2::new(self.x + self.width as i32 / 2, self.y) 33 } 34 top_right_pos(&self) -> Vector235 pub fn top_right_pos(&self) -> Vector2 { 36 Vector2::new(self.x + self.width as i32, self.y) 37 } 38 left_pos(&self) -> Vector239 pub fn left_pos(&self) -> Vector2 { 40 Vector2::new(self.x, self.y + self.height as i32 / 2) 41 } 42 center_pos(&self) -> Vector243 pub fn center_pos(&self) -> Vector2 { 44 Vector2::new( 45 self.x + self.width as i32 / 2, 46 self.y + self.height as i32 / 2, 47 ) 48 } 49 right_pos(&self) -> Vector250 pub fn right_pos(&self) -> Vector2 { 51 Vector2::new(self.x + self.width as i32, self.y + self.height as i32 / 2) 52 } 53 bottom_left_pos(&self) -> Vector254 pub fn bottom_left_pos(&self) -> Vector2 { 55 Vector2::new(self.x, self.y + self.height as i32) 56 } 57 bottom_pos(&self) -> Vector258 pub fn bottom_pos(&self) -> Vector2 { 59 Vector2::new(self.x + self.width as i32 / 2, self.y + self.height as i32) 60 } 61 bottom_right_pos(&self) -> Vector262 pub fn bottom_right_pos(&self) -> Vector2 { 63 Vector2::new(self.x + self.width as i32, self.y + self.height as i32) 64 } 65 66 /// 判断该矩形是否包含某点 contains(&self, p: Vector2) -> bool67 pub fn contains(&self, p: Vector2) -> bool { 68 p.x >= self.x 69 && p.x < self.x + self.width as i32 70 && p.y >= self.y 71 && p.y < self.y + self.height as i32 72 } 73 74 /// 判断该矩形是否完全包含另一个矩形 contains_rect(&self, r: &Rect) -> bool75 pub fn contains_rect(&self, r: &Rect) -> bool { 76 let p1 = r.top_left_pos(); 77 let p2 = p1 + Vector2::new(r.width as i32, r.height as i32); 78 self.contains(p1) && self.contains(p2) 79 } 80 81 // 判断该矩形是否和另一矩形有重叠部分 intersects(&self, r: &Rect) -> bool82 pub fn intersects(&self, r: &Rect) -> bool { 83 !(r.x >= (self.x + self.width as i32) 84 || self.x >= (r.x + r.width as i32) 85 || r.y >= (self.y + self.height as i32) 86 || self.y >= (r.y + r.height as i32)) 87 } 88 } 89