lighthouse_protocol/input/
gamepad_event.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Direction;
4
5use super::{EventSource, GamepadControlEvent};
6
7/// A gamepad/controller event.
8#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
9#[serde(rename_all = "camelCase")]
10pub struct GamepadEvent {
11    /// The client identifier. Also unique per gamepad.
12    pub source: EventSource,
13    /// The control-specific info.
14    #[serde(flatten)]
15    pub control: GamepadControlEvent,
16}
17
18impl GamepadEvent {
19    /// Parses the gamepad event as an arbitrary direction.
20    pub fn direction(&self) -> Option<Direction> {
21        self.left_direction().or_else(|| self.right_direction())
22    }
23
24    /// The direction if the gamepad event represents a D-pad or left stick.
25    /// Commonly used e.g. for movement in games.
26    pub fn left_direction(&self) -> Option<Direction> {
27        match &self.control {
28            GamepadControlEvent::Button(button) => button.d_pad_direction(),
29            GamepadControlEvent::Axis2D(axis2d) if axis2d.index == 0 => axis2d.direction(),
30            _ => None,
31        }
32    }
33
34    /// The direction if the gamepad event represents a right stick event.
35    /// Commonly used e.g. for camera control in games.
36    pub fn right_direction(&self) -> Option<Direction> {
37        match &self.control {
38            GamepadControlEvent::Axis2D(axis2d) if axis2d.index == 1 => axis2d.direction(),
39            _ => None,
40        }
41    }
42}