Skip to content

Commit b77b549

Browse files
committed
Add helpers for extracting direction from KeyEvent
1 parent e910eb3 commit b77b549

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

lighthouse-protocol/src/input/key_event.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use serde::{Deserialize, Serialize};
22

3+
use crate::{Delta, Unity, Zero};
4+
35
use super::{EventSource, KeyModifiers};
46

57
/// A keyboard event.
@@ -17,3 +19,32 @@ pub struct KeyEvent {
1719
/// The held key modifiers.
1820
pub modifiers: KeyModifiers,
1921
}
22+
23+
impl KeyEvent {
24+
/// The direction if either the WASD or arrow keys were pressed.
25+
pub fn direction<T>(&self) -> Option<Delta<T>> where T: Zero + Unity {
26+
self.wasd_direction().or_else(|| self.arrow_direction())
27+
}
28+
29+
/// The direction if one of the WASD keys was pressed.
30+
pub fn wasd_direction<T>(&self) -> Option<Delta<T>> where T: Zero + Unity {
31+
match self.code.as_str() {
32+
"KeyW" => Some(Delta::UP),
33+
"KeyA" => Some(Delta::LEFT),
34+
"KeyS" => Some(Delta::DOWN),
35+
"KeyD" => Some(Delta::RIGHT),
36+
_ => None,
37+
}
38+
}
39+
40+
/// The direction if one of the arrow keys was pressed.
41+
pub fn arrow_direction<T>(&self) -> Option<Delta<T>> where T: Zero + Unity {
42+
match self.code.as_str() {
43+
"ArrowUp" => Some(Delta::UP),
44+
"ArrowLeft" => Some(Delta::LEFT),
45+
"ArrowDown" => Some(Delta::DOWN),
46+
"ArrowRight" => Some(Delta::RIGHT),
47+
_ => None,
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)