diff --git a/src/input.rs b/src/input.rs index 29fb1f4b..9768ac17 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,26 @@ 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(),