-
Notifications
You must be signed in to change notification settings - Fork 6
/
keyhandler.js
65 lines (55 loc) · 1.09 KB
/
keyhandler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var raycast = raycast || {};
raycast.keyhandler = (function () {
var codes = {
up: 38,
w: 87,
down: 40,
left: 37,
a: 65,
right: 39,
d: 68,
space: 32,
ctrl: 17,
esc: 27
};
var state = new Array();
var lastState = new Array();
for (var i = 0; i < 255; i++) {
state[i] = false;
lastState[i] = false;
}
onKeyup = function (e) {
state[e.which] = false;
if (isUsedKey(e.which))
e.preventDefault();
}
onKeydown = function (e) {
state[e.which] = true;
if (isUsedKey(e.which))
e.preventDefault();
}
function isUsedKey(keycode) {
for (var key in codes) {
if (codes[key] == keycode) {
return true;
}
}
return false;
}
isKeydown = function(keyname) {
return state[codes[keyname]];
}
isKeypress = function(keyname) {
return state[codes[keyname]] && !lastState[codes[keyname]];
}
tick = function() {
lastState = state.slice();
}
return {
onKeyup: onKeyup,
onKeydown: onKeydown,
isKeydown: isKeydown,
isKeypress: isKeypress,
tick: tick
};
})();