moon_engine/
input.rs

1//! The [`InputManager`] struct.
2
3use std::collections::BTreeSet;
4
5use crate::Vec2;
6
7/// A store for Input-related data.
8///
9/// The [`InputManager`] stores and handles the current input states.
10///
11/// # Examples
12/// ```
13/// use moon_engine::input::InputManager;
14///
15/// let mut input = InputManager::new();
16///
17/// input.key_down(b'w');
18///
19/// assert!(input.get_key_state(b'w'));
20/// ```
21#[derive(Default)]
22pub struct InputManager {
23    /// Set of Keyboard key states.
24    ///
25    /// If a key is present, then it is being pressed, and otherwise it is not.
26    keyboard_states: BTreeSet<u8>,
27    /// Position of the Mouse.
28    ///
29    /// The Screen-Space position of the Mouse as a [`Vec2`].
30    pub mouse_position: Vec2,
31}
32
33impl InputManager {
34    /// Default [`InputManager`] instance.
35    ///
36    /// Creates a new [`InputManager`] with default keyboard and mouse input states.
37    pub fn new() -> Self {
38        Default::default()
39    }
40
41    /// Key Down State.
42    ///
43    /// Sets the key in the [`BTreeSet`].
44    pub fn key_down(&mut self, key_code: u8) {
45        self.keyboard_states.insert(key_code);
46    }
47
48    /// Key Up State.
49    ///
50    /// Resets the key in the [`BTreeSet`].
51    pub fn key_up(&mut self, key_code: u8) {
52        self.keyboard_states.remove(&key_code);
53    }
54
55    /// Get the state of a key as a [`bool`].
56    ///
57    /// Returns true if the key is currently pressed, or false.
58    pub fn get_key_state(&self, key_code: u8) -> bool {
59        self.keyboard_states.contains(&key_code)
60    }
61
62    /// Set the mouse position.
63    pub fn set_mouse_position(&mut self, x: f32, y: f32) {
64        self.mouse_position.x = x;
65        self.mouse_position.y = y;
66    }
67}