fennel_physics/aabb.rs
1use nalgebra::Vector3;
2
3/// Structure representing the bounding box
4#[derive(Debug)]
5pub struct BoundingBox {
6 /// Width of the bounding box
7 pub width: f32,
8 /// Height of the bounding box
9 pub height: f32,
10 /// Position of the bounding box.
11 /// Use `0.0` for the third value and ignore it if the bounding box is in a 2D dimension
12 pub position: Vector3<f32>,
13}
14
15impl BoundingBox {
16 /// Creates a new instance of [`BoundingBox`]
17 ///
18 /// # Arguments
19 /// * `width`: width of the bounding box
20 /// * `height`: height of the bounding box
21 /// * `position`: `Vector3<f32>` of the bounding box. Use `0.0` for the third (z) value if the box is in a 2D dimension
22 pub fn new(width: f32, height: f32, position: Vector3<f32>) -> Self {
23 Self {
24 width,
25 height,
26 position,
27 }
28 }
29
30 /// Checks if a collision happened between two bounding boxes
31 ///
32 /// # Arguments
33 /// * `other`: immutable reference to a box with which the collision should be checked
34 ///
35 /// # Examples
36 /// ```
37 /// use nalgebra::Vector3;
38 /// use fennel_physics::aabb::BoundingBox;
39 /// let first_box = BoundingBox::new(10.0, 10.0, Vector3::new(3.0, 4.0, 0.0)); // 2d plane
40 /// let second_box = BoundingBox::new(10.0, 10.0, Vector3::new(3.0, 6.0, 0.0));
41 /// assert!(first_box.check_collision(&second_box)); // boxes collide
42 /// ```
43 pub fn check_collision(&self, other: &BoundingBox) -> bool {
44 other.position.x >= self.position.x &&
45 other.position.x <= self.position.x + self.width &&
46 other.position.y >= self.position.y &&
47 other.position.y <= self.position.y + self.height &&
48 other.position.z >= self.position.z
49 }
50}