Skip to content

Commit 0a0c09c

Browse files
committed
added is_key_repeated
1 parent fbc812d commit 0a0c09c

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/input.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ use crate::Vec2;
88
use crate::{get_context, DroppedFile};
99
pub use miniquad::{KeyCode, MouseButton};
1010

11+
const KEY_REPEAT_DELAY: f64 = 5.0;
12+
1113
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1214
pub enum TouchPhase {
1315
Started,
@@ -132,6 +134,30 @@ pub fn is_key_released(key_code: KeyCode) -> bool {
132134
context.keys_released.contains(&key_code)
133135
}
134136

137+
/// Detect if the key has been pressed for some time
138+
pub fn is_key_repeated(key_code: KeyCode) -> bool {
139+
let context = get_context();
140+
141+
// stores the amount of time each key has been pressed for
142+
let time_map = &mut context.keys_repeated;
143+
144+
time_map
145+
.entry(key_code)
146+
.or_insert(0.);
147+
148+
let time_pressed = time_map
149+
.get_mut(&key_code)
150+
.unwrap();
151+
152+
if is_key_down(key_code) {
153+
*time_pressed += 1.;
154+
} else {
155+
*time_pressed = 0.;
156+
}
157+
158+
*time_pressed >= KEY_REPEAT_DELAY
159+
}
160+
135161
/// Return the last pressed char.
136162
/// Each "get_char_pressed" call will consume a character from the input queue.
137163
pub fn get_char_pressed() -> Option<char> {

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ struct Context {
185185
keys_down: HashSet<KeyCode>,
186186
keys_pressed: HashSet<KeyCode>,
187187
keys_released: HashSet<KeyCode>,
188+
keys_repeated: HashMap<KeyCode, f64>,
188189
mouse_down: HashSet<MouseButton>,
189190
mouse_pressed: HashSet<MouseButton>,
190191
mouse_released: HashSet<MouseButton>,
@@ -321,6 +322,7 @@ impl Context {
321322
keys_down: HashSet::new(),
322323
keys_pressed: HashSet::new(),
323324
keys_released: HashSet::new(),
325+
keys_repeated: HashMap::new(),
324326
chars_pressed_queue: Vec::new(),
325327
chars_pressed_ui_queue: Vec::new(),
326328
mouse_down: HashSet::new(),

0 commit comments

Comments
 (0)