From a854f5d329e0ee8f31f4904d4c0dc5b2da78fda8 Mon Sep 17 00:00:00 2001 From: Jarrod Doyle Date: Fri, 8 Mar 2024 07:36:49 +0000 Subject: [PATCH] Simple input manager --- src/input.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 31 ++++++++++++++++++++++--------- 2 files changed, 74 insertions(+), 9 deletions(-) create mode 100644 src/input.rs diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..f668a6b --- /dev/null +++ b/src/input.rs @@ -0,0 +1,52 @@ +use winit::{event::WindowEvent, keyboard::KeyCode}; + +pub struct Input { + keys_held: Vec, + keys_just_pressed: Vec, + keys_just_released: Vec, + // TODO: Modifiers +} + +impl Input { + pub fn new() -> Self { + Self { + keys_held: vec![], + keys_just_pressed: vec![], + keys_just_released: vec![], + } + } + + pub fn update(&mut self, event: &WindowEvent) { + self.keys_just_pressed.clear(); + self.keys_just_released.clear(); + + if let WindowEvent::KeyboardInput { event, .. } = event { + let keycode = match event.physical_key { + winit::keyboard::PhysicalKey::Code(code) => code, + _ => KeyCode::Abort, + }; + match event.state { + winit::event::ElementState::Pressed => { + self.keys_held.push(keycode); + self.keys_just_pressed.push(keycode); + } + winit::event::ElementState::Released => { + self.keys_held.retain(|v| *v != keycode); + self.keys_just_released.push(keycode); + } + } + } + } + + pub fn is_key_pressed(&self, key: KeyCode) -> bool { + self.keys_held.contains(&key) + } + + pub fn is_key_just_pressed(&self, key: KeyCode) -> bool { + self.keys_just_pressed.contains(&key) + } + + pub fn is_key_just_released(&self, key: KeyCode) -> bool { + self.keys_just_released.contains(&key) + } +} diff --git a/src/main.rs b/src/main.rs index 11c07ef..4a563aa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,15 @@ mod gfx; +mod input; use anyhow::Result; use gfx::Context; +use input::Input; use wgpu::Limits; use winit::{ dpi::LogicalSize, event::*, event_loop::{ControlFlow, EventLoop}, + keyboard::KeyCode, window::{Window, WindowBuilder}, }; @@ -21,18 +24,28 @@ pub fn main() -> Result<()> { } pub fn run(event_loop: EventLoop<()>, mut context: Context) -> Result<()> { - event_loop.run(|event, elwt| match event { - Event::WindowEvent { window_id, event } if window_id == context.window.id() => { - if context.handle_window_event(&event, elwt) { - return; - } + let mut input = Input::new(); - if let WindowEvent::RedrawRequested = event { - render(&context); - context.window.request_redraw(); + event_loop.run(|event, elwt| { + match event { + Event::WindowEvent { window_id, event } if window_id == context.window.id() => { + if context.handle_window_event(&event, elwt) { + return; + } + + if let WindowEvent::RedrawRequested = event { + render(&context); + context.window.request_redraw(); + } + + input.update(&event); } + _ => (), + } + + if input.is_key_just_pressed(KeyCode::Escape) { + elwt.exit(); } - _ => (), })?; Ok(())