Huge input update, FPS Camera controls system
Long day. I now store winit:🪟:Window in a mutex.
This commit is contained in:
parent
1e9b997aeb
commit
46c8c32819
15 changed files with 307 additions and 39 deletions
69
engine/src/input.rs
Normal file
69
engine/src/input.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue