-
Notifications
You must be signed in to change notification settings - Fork 0
/
Input.js
69 lines (58 loc) · 1.81 KB
/
Input.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
66
67
68
69
export default class Input {
/**
* @type {Array<string>}
*/
static PressedKeys = [];
static mouseDown = false;
/**
* @type {Array<(ev:Event)>}
*/
static scrollListeners = [];
static mousePos = {
x: 0,
y: 0
}
/**
* Initializes the `Input` class, this only has to be done once, it is done right before the game starts, when `HTML5Game.Start();` is called
*/
constructor() {
window.addEventListener("keydown", function(ev) {
if (!Input.PressedKeys.includes(ev.key.toLowerCase())) {
Input.PressedKeys.push(ev.key.toLowerCase());
}
});
window.addEventListener("keyup", function(ev) {
Input.PressedKeys.splice(Input.PressedKeys.indexOf(ev.key.toLowerCase()), 1);
});
window.addEventListener("mousedown", function(ev) {
Input.mouseDown = true;
});
window.addEventListener("mouseup", function(ev) {
Input.mouseDown = false;
});
window.addEventListener("scroll", function(ev) {
Input.scrollListeners.forEach(function(value) {
value(ev);
});
});
window.addEventListener("mousemove", function(ev) {
Input.mousePos.x = ev.clientX;
Input.mousePos.y = ev.clientY;
});
}
/**
* Adds an event listener to track scroll events
* @param {(ev:Event)} callback
*/
static addScrollListener(callback) {
Input.scrollListeners.push(callback);
}
/**
* Checks if a key is pressed
* @param {string} key The key to check
* @returns
*/
static isKeyDown(key) {
return Input.PressedKeys.includes(key);
}
}