From 0a0c09c241a6ab119c70cd8e7a7014137cdc22fa Mon Sep 17 00:00:00 2001 From: lukasx999 <116069013+lukasx999@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:17:26 +0200 Subject: [PATCH 1/2] added is_key_repeated --- src/input.rs | 26 ++++++++++++++++++++++++++ src/lib.rs | 2 ++ 2 files changed, 28 insertions(+) diff --git a/src/input.rs b/src/input.rs index 29fb1f4b..3665953c 100644 --- a/src/input.rs +++ b/src/input.rs @@ -8,6 +8,8 @@ use crate::Vec2; use crate::{get_context, DroppedFile}; pub use miniquad::{KeyCode, MouseButton}; +const KEY_REPEAT_DELAY: f64 = 5.0; + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum TouchPhase { Started, @@ -132,6 +134,30 @@ pub fn is_key_released(key_code: KeyCode) -> bool { context.keys_released.contains(&key_code) } +/// Detect if the key has been pressed for some time +pub fn is_key_repeated(key_code: KeyCode) -> bool { + let context = get_context(); + + // stores the amount of time each key has been pressed for + let time_map = &mut context.keys_repeated; + + time_map + .entry(key_code) + .or_insert(0.); + + let time_pressed = time_map + .get_mut(&key_code) + .unwrap(); + + if is_key_down(key_code) { + *time_pressed += 1.; + } else { + *time_pressed = 0.; + } + + *time_pressed >= KEY_REPEAT_DELAY +} + /// Return the last pressed char. /// Each "get_char_pressed" call will consume a character from the input queue. pub fn get_char_pressed() -> Option { diff --git a/src/lib.rs b/src/lib.rs index fe53e211..a23a4835 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -185,6 +185,7 @@ struct Context { keys_down: HashSet, keys_pressed: HashSet, keys_released: HashSet, + keys_repeated: HashMap, mouse_down: HashSet, mouse_pressed: HashSet, mouse_released: HashSet, @@ -321,6 +322,7 @@ impl Context { keys_down: HashSet::new(), keys_pressed: HashSet::new(), keys_released: HashSet::new(), + keys_repeated: HashMap::new(), chars_pressed_queue: Vec::new(), chars_pressed_ui_queue: Vec::new(), mouse_down: HashSet::new(), From 8956d2f6baa46335a9e0cff00449e74953461080 Mon Sep 17 00:00:00 2001 From: lukasx999 <116069013+lukasx999@users.noreply.github.com> Date: Sun, 27 Apr 2025 17:23:29 +0200 Subject: [PATCH 2/2] formatting --- src/input.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/input.rs b/src/input.rs index 3665953c..9768ac17 100644 --- a/src/input.rs +++ b/src/input.rs @@ -141,13 +141,9 @@ pub fn is_key_repeated(key_code: KeyCode) -> bool { // stores the amount of time each key has been pressed for let time_map = &mut context.keys_repeated; - time_map - .entry(key_code) - .or_insert(0.); + time_map.entry(key_code).or_insert(0.); - let time_pressed = time_map - .get_mut(&key_code) - .unwrap(); + let time_pressed = time_map.get_mut(&key_code).unwrap(); if is_key_down(key_code) { *time_pressed += 1.;