Skip to main content

resphys/object/
builder.rs

1pub use super::super::collision::AABB;
2pub use super::{Body, BodyHandle, BodyStatus, Collider, ColliderState};
3use glam::Vec2;
4
5/// Builder for the `Body`. Start with `new`, finish with `build`.
6#[derive(Debug, Clone)]
7pub struct BodyDesc {
8    pub position: Vec2,
9
10    pub velocity: Vec2,
11    pub status: BodyStatus,
12    pub self_collide: bool,
13}
14
15impl Default for BodyDesc {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl BodyDesc {
22    pub fn new() -> Self {
23        Self {
24            position: Vec2::zero(),
25            velocity: Vec2::zero(),
26            status: BodyStatus::Kinematic,
27            self_collide: true,
28        }
29    }
30    pub fn with_position(mut self, position: Vec2) -> Self {
31        self.position = position;
32        self
33    }
34    pub fn with_velocity(mut self, velocity: Vec2) -> Self {
35        self.velocity = velocity;
36        self
37    }
38    pub fn make_static(mut self) -> Self {
39        self.status = BodyStatus::Static;
40        self
41    }
42    pub fn self_collision(mut self, check: bool) -> Self {
43        self.self_collide = check;
44        self
45    }
46    pub fn build(self) -> Body {
47        Body::new(self.position, self.velocity, self.status, self.self_collide)
48    }
49}
50
51// Builder for the `Collider`. Start with `new`, finish with `build`.
52#[derive(Debug, Clone)]
53pub struct ColliderDesc<T> {
54    pub shape: AABB,
55    pub offset: Vec2,
56    pub state: ColliderState,
57
58    pub category_bits: u32,
59    pub mask_bits: u32,
60
61    pub user_tag: T,
62}
63
64impl<T: Copy> ColliderDesc<T> {
65    pub fn new(shape: AABB, user_tag: T) -> Self {
66        Self {
67            shape,
68            offset: Vec2::zero(),
69            state: ColliderState::Solid,
70            category_bits: 1,
71            mask_bits: u32::MAX,
72            user_tag,
73        }
74    }
75    pub fn with_shape(mut self, shape: AABB) -> Self {
76        self.shape = shape;
77        self
78    }
79    pub fn with_offset(mut self, offset: Vec2) -> Self {
80        self.offset = offset;
81        self
82    }
83    pub fn sensor(mut self) -> Self {
84        self.state = ColliderState::Sensor;
85        self
86    }
87    pub fn with_category(mut self, category_bits: u32) -> Self {
88        self.category_bits = category_bits;
89        self
90    }
91    pub fn with_mask(mut self, mask_bits: u32) -> Self {
92        self.mask_bits = mask_bits;
93        self
94    }
95    pub fn with_tag(mut self, user_tag: T) -> Self {
96        self.user_tag = user_tag;
97        self
98    }
99    pub fn build(self, owner: BodyHandle) -> Collider<T> {
100        Collider::new(
101            self.shape,
102            self.offset,
103            self.state,
104            self.category_bits,
105            self.mask_bits,
106            self.user_tag,
107            owner,
108        )
109    }
110}