sfml_xt/
window.rs

1use {sfml::window::mouse, std::collections::HashSet};
2
3use sfml::window::{Event, Key};
4
5/// Input abstraction that collects input state from events.
6///
7/// Unlike Key::is_pressed(), events only trigger if the window is focused
8#[derive(Default)]
9pub struct InputState {
10    keys_down: HashSet<Key>,
11    mouse_down: HashSet<mouse::Button>,
12    mouse_pressed: HashSet<mouse::Button>,
13}
14
15impl InputState {
16    /// Call at start of frame to clear "pressed" state
17    pub fn start_frame(&mut self) {
18        self.mouse_pressed.clear();
19    }
20    /// Update from an `Event`. Use this in your event polling loop.
21    pub fn update_from_event(&mut self, event: &Event) {
22        match event {
23            Event::KeyPressed { code, .. } => {
24                self.keys_down.insert(*code);
25            }
26            Event::KeyReleased { code, .. } => {
27                self.keys_down.remove(code);
28            }
29            Event::MouseButtonPressed { button, .. } => {
30                self.mouse_down.insert(*button);
31                self.mouse_pressed.insert(*button);
32            }
33            Event::MouseButtonReleased { button, .. } => {
34                self.mouse_down.remove(button);
35            }
36            _ => {}
37        }
38    }
39    /// Returns whether `key` is being held down
40    pub fn key_down(&self, key: Key) -> bool {
41        self.keys_down.contains(&key)
42    }
43    /// Returns whether `button` is being held down
44    pub fn mouse_down(&self, button: mouse::Button) -> bool {
45        self.mouse_down.contains(&button)
46    }
47    /// Returns whether `button` was pressed this frame
48    pub fn mouse_pressed(&self, button: mouse::Button) -> bool {
49        self.mouse_pressed.contains(&button)
50    }
51}