Simple input manager

This commit is contained in:
Jarrod Doyle 2024-03-08 07:36:49 +00:00
parent 4cd1a3e7cd
commit a854f5d329
Signed by: Jayrude
GPG Key ID: 38B57B16E7C0ADF7
2 changed files with 74 additions and 9 deletions

52
src/input.rs Normal file
View File

@ -0,0 +1,52 @@
use winit::{event::WindowEvent, keyboard::KeyCode};
pub struct Input {
keys_held: Vec<KeyCode>,
keys_just_pressed: Vec<KeyCode>,
keys_just_released: Vec<KeyCode>,
// 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)
}
}

View File

@ -1,12 +1,15 @@
mod gfx; mod gfx;
mod input;
use anyhow::Result; use anyhow::Result;
use gfx::Context; use gfx::Context;
use input::Input;
use wgpu::Limits; use wgpu::Limits;
use winit::{ use winit::{
dpi::LogicalSize, dpi::LogicalSize,
event::*, event::*,
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
keyboard::KeyCode,
window::{Window, WindowBuilder}, window::{Window, WindowBuilder},
}; };
@ -21,7 +24,10 @@ pub fn main() -> Result<()> {
} }
pub fn run(event_loop: EventLoop<()>, mut context: Context) -> Result<()> { pub fn run(event_loop: EventLoop<()>, mut context: Context) -> Result<()> {
event_loop.run(|event, elwt| match event { let mut input = Input::new();
event_loop.run(|event, elwt| {
match event {
Event::WindowEvent { window_id, event } if window_id == context.window.id() => { Event::WindowEvent { window_id, event } if window_id == context.window.id() => {
if context.handle_window_event(&event, elwt) { if context.handle_window_event(&event, elwt) {
return; return;
@ -31,8 +37,15 @@ pub fn run(event_loop: EventLoop<()>, mut context: Context) -> Result<()> {
render(&context); render(&context);
context.window.request_redraw(); context.window.request_redraw();
} }
input.update(&event);
} }
_ => (), _ => (),
}
if input.is_key_just_pressed(KeyCode::Escape) {
elwt.exit();
}
})?; })?;
Ok(()) Ok(())