Created
October 23, 2018 13:35
-
-
Save Darksecond/05a685431d22f3c833ef86f69d5080f8 to your computer and use it in GitHub Desktop.
Proper Keyboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const KEY_TAB = 9; | |
export const KEY_SHIFT = 16; | |
export const KEY_CONTROL = 17; | |
export const KEY_ALT = 18; | |
export const KEY_SPACE = 32; | |
export const KEY_LEFT = 37; | |
export const KEY_UP = 38; | |
export const KEY_RIGHT = 39; | |
export const KEY_DOWN = 40; | |
export const KEY_E = 69; | |
export const KEY_W = 87; | |
export const KEY_A = 65; | |
export const KEY_D = 68; | |
export const KEY_Q = 81; | |
export const KEY_S = 83; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// False -> Up, True -> Down | |
const pressedKeys: { [key:number]: boolean } = {}; | |
const mappedKeys: { [from: number]: /*to*/ number} = {}; | |
document.addEventListener("keydown", (e: KeyboardEvent)=>{ | |
let keyCode = mappedKeys[e.keyCode] || e.keyCode; | |
if(pressedKeys[keyCode] !== undefined) { | |
e.preventDefault(); | |
pressedKeys[keyCode] = true; | |
} | |
}); | |
document.addEventListener("keyup", (e: KeyboardEvent) => { | |
let keyCode = mappedKeys[e.keyCode] || e.keyCode; | |
if (pressedKeys[keyCode] !== undefined) { | |
e.preventDefault(); | |
pressedKeys[keyCode] = false; | |
} | |
}); | |
export function register(...keys: number[]) { | |
for (let key of keys) { | |
pressedKeys[key] = false; | |
} | |
} | |
export function deregister(...keys: number[]) { | |
for(let key of keys) { | |
delete pressedKeys[key]; | |
} | |
} | |
export function map(from: number, to: number) { | |
mappedKeys[from] = to; | |
} | |
export function unmap(from: number) { | |
delete mappedKeys[from]; | |
} | |
export function isDown(key: number): boolean { | |
return pressedKeys[key] || false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment