69 lines
2.1 KiB
Rust
69 lines
2.1 KiB
Rust
use std::collections::HashSet;
|
|
use winit::event::{ElementState, Event, MouseButton, WindowEvent};
|
|
use winit::keyboard::{KeyCode, PhysicalKey};
|
|
|
|
/// A utility to help with buffering input.
|
|
/// Meant to be plugged into systems.
|
|
#[derive(Default, Clone, Debug)]
|
|
pub struct InputState {
|
|
held_keys: HashSet<KeyCode>,
|
|
held_mouse: HashSet<MouseButton>,
|
|
}
|
|
|
|
impl InputState {
|
|
fn new() -> Self {
|
|
Default::default()
|
|
}
|
|
|
|
pub fn handle_event(&mut self, event: &Event<()>) {
|
|
if let Event::WindowEvent { event, .. } = event {
|
|
match event {
|
|
// Keyboard
|
|
WindowEvent::KeyboardInput { event: key_event, .. } => {
|
|
if let PhysicalKey::Code(code) = key_event.physical_key {
|
|
match key_event.state {
|
|
ElementState::Pressed => {
|
|
self.held_keys.insert(code);
|
|
}
|
|
ElementState::Released => {
|
|
self.held_keys.remove(&code);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Mouse
|
|
WindowEvent::MouseInput { state, button, .. } => {
|
|
match state {
|
|
ElementState::Pressed => {
|
|
self.held_mouse.insert(*button);
|
|
}
|
|
ElementState::Released => {
|
|
self.held_mouse.remove(button);
|
|
}
|
|
}
|
|
}
|
|
|
|
WindowEvent::Focused(focused) => {
|
|
if !*focused {
|
|
self.clear();
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn key_held(&self, code: KeyCode) -> bool {
|
|
self.held_keys.contains(&code)
|
|
}
|
|
|
|
pub fn mouse_held(&self, button: MouseButton) -> bool {
|
|
self.held_mouse.contains(&button)
|
|
}
|
|
|
|
pub fn clear(&mut self) {
|
|
self.held_keys.clear();
|
|
self.held_mouse.clear();
|
|
}
|
|
}
|