11use serde:: { Deserialize , Serialize } ;
22
3+ use crate :: { Delta , Unity , Zero } ;
4+
35use 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