Skip to main content

mittens_engine/engine/ecs/component/
gravity.rs

1use crate::engine::ecs::ComponentId;
2use crate::engine::ecs::component::Component;
3
4/// Gravity field component.
5///
6/// Any `KineticResponseComponent` nested under a `GravityComponent` will have gravity applied
7/// by `KineticResponseSystem`.
8///
9/// This component can live anywhere in the scene graph and can have arbitrary descendants.
10/// If multiple `GravityComponent`s exist in the ancestor chain, the nearest enabled one wins.
11#[derive(Debug, Clone)]
12pub struct GravityComponent {
13    pub enabled: bool,
14
15    /// Multiplier applied to the system gravity (m/s^2).
16    ///
17    /// - `1.0` = earth-like gravity
18    /// - `0.0` = no gravity
19    /// - negative values invert gravity
20    pub coefficient: f32,
21
22    component: Option<ComponentId>,
23}
24
25impl GravityComponent {
26    pub fn new() -> Self {
27        Self {
28            enabled: true,
29            coefficient: 1.0,
30            component: None,
31        }
32    }
33
34    pub fn off() -> Self {
35        Self {
36            enabled: false,
37            coefficient: 0.0,
38            component: None,
39        }
40    }
41
42    pub fn with_coefficient(mut self, coefficient: f32) -> Self {
43        self.coefficient = coefficient;
44        self
45    }
46}
47
48impl Default for GravityComponent {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Component for GravityComponent {
55    fn name(&self) -> &'static str {
56        "gravity"
57    }
58
59    fn set_id(&mut self, component: ComponentId) {
60        self.component = Some(component);
61    }
62
63    fn as_any(&self) -> &dyn std::any::Any {
64        self
65    }
66
67    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
68        self
69    }
70
71    fn init(&mut self, _emit: &mut dyn crate::engine::ecs::SignalEmitter, _component: ComponentId) {
72    }
73
74    fn cleanup(
75        &mut self,
76        _emit: &mut dyn crate::engine::ecs::SignalEmitter,
77        _component: ComponentId,
78    ) {
79    }
80
81    fn to_mms_ast(
82        &self,
83        _world: &crate::engine::ecs::World,
84    ) -> crate::scripting::ast::ComponentExpression {
85        use crate::engine::ecs::component::ce_helpers::*;
86        ce("Gravity")
87            .with_call("enabled", vec![b(self.enabled)])
88            .with_call("coefficient", vec![num(self.coefficient as f64)])
89    }
90}