Simple input manager
This commit is contained in:
parent
4cd1a3e7cd
commit
a854f5d329
|
@ -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)
|
||||
}
|
||||
}
|
15
src/main.rs
15
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,7 +24,10 @@ pub fn main() -> 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() => {
|
||||
if context.handle_window_event(&event, elwt) {
|
||||
return;
|
||||
|
@ -31,8 +37,15 @@ pub fn run(event_loop: EventLoop<()>, mut context: Context) -> Result<()> {
|
|||
render(&context);
|
||||
context.window.request_redraw();
|
||||
}
|
||||
|
||||
input.update(&event);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
|
||||
if input.is_key_just_pressed(KeyCode::Escape) {
|
||||
elwt.exit();
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
|
|
Loading…
Reference in New Issue