bevy_enhanced_input/preset/
axial.rs

1use bevy::{ecs::spawn::SpawnableList, prelude::*, ptr::MovingPtr};
2
3use crate::prelude::*;
4
5/// A preset to map 2 axes as 2-dimensional input.
6#[derive(Debug, Clone, Copy)]
7pub struct Axial<X, Y> {
8    pub x: X,
9    pub y: Y,
10}
11
12impl<X, Y, T: Clone> WithBundle<T> for Axial<X, Y> {
13    type Output = Axial<(X, T), (Y, T)>;
14
15    fn with(self, bundle: T) -> Self::Output {
16        Axial {
17            x: (self.x, bundle.clone()),
18            y: (self.y, bundle),
19        }
20    }
21}
22
23impl Axial<Binding, Binding> {
24    /// Maps left stick as 2-dimensional input.
25    #[must_use]
26    pub fn left_stick() -> Self {
27        Self::new(GamepadAxis::LeftStickX, GamepadAxis::LeftStickY)
28    }
29
30    /// Maps right stick as 2-dimensional input.
31    #[must_use]
32    pub fn right_stick() -> Self {
33        Self::new(GamepadAxis::RightStickX, GamepadAxis::RightStickY)
34    }
35
36    /// Maps 2 bindings as 2-dimensional input.
37    #[must_use]
38    pub fn new(x: impl Into<Binding>, y: impl Into<Binding>) -> Self {
39        Self {
40            x: x.into(),
41            y: y.into(),
42        }
43    }
44
45    /// Applies keyboard modifiers to all bindings.
46    #[must_use]
47    pub fn with_mod_keys(self, mod_keys: ModKeys) -> Self {
48        Self {
49            x: self.x.with_mod_keys(mod_keys),
50            y: self.y.with_mod_keys(mod_keys),
51        }
52    }
53}
54
55impl<X: Bundle, Y: Bundle> SpawnableList<BindingOf> for Axial<X, Y> {
56    fn spawn(this: MovingPtr<'_, Self>, world: &mut World, entity: Entity) {
57        let axial = this.read();
58        world.spawn((BindingOf(entity), axial.x));
59        world.spawn((BindingOf(entity), axial.y, SwizzleAxis::YXZ));
60    }
61
62    fn size_hint(&self) -> usize {
63        2
64    }
65}