forked from arpruss/rjmscratch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplegamepad.js
executable file
·83 lines (79 loc) · 3.01 KB
/
simplegamepad.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class ScratchSimpleGamepad {
constructor(runtime) {
this.runtime = runtime
this.currentMSecs = -1
this.previousButtons = []
this.currentButtons = []
}
getInfo() {
return {
"id": "SimpleGamepad",
"name": "SimpleGamepad",
"blocks": [{
"opcode": "buttonPressedReleased",
"blockType": "hat",
"text": "button [b] [eventType]",
"arguments": {
"b": {
"type": "number",
"defaultValue": "0"
},
"eventType": {
"type": "number",
"defaultValue": "1",
"menu": "pressReleaseMenu"
},
},
},
],
"menus": {
"pressReleaseMenu": [{text:"press",value:1}, {text:"release",value:0}],
}
};
}
update() {
if (this.runtime.currentMSecs == this.currentMSecs)
return // not a new polling cycle
this.currentMSecs = this.runtime.currentMSecs
var gamepads = navigator.getGamepads()
if (gamepads == null || gamepads.length == 0 || gamepads[0] == null) {
// different number of buttons, so new gamepad
this.previousButtons = []
this.currentButtons = []
return
}
var gamepad = gamepads[0]
if (gamepad.buttons.length != this.previousButtons.length) {
this.previousButtons = []
for (var i = 0; i < gamepad.buttons.length; i++)
this.previousButtons.push(false)
}
else {
this.previousButtons = this.currentButtons
}
this.currentButtons = []
for (var i = 0; i < gamepad.buttons.length; i++)
this.currentButtons.push(gamepad.buttons[i].pressed)
}
buttonPressedReleased({b,eventType}) {
this.update()
if (b < this.currentButtons.length) {
if (eventType == 1) { // note: this will be a string, so better to compare it to 1 than to treat it as a Boolean
if (this.currentButtons[b] && ! this.previousButtons[b]) {
return true
}
}
else {
if (!this.currentButtons[b] && this.previousButtons[b]) {
return true
}
}
}
return false
}
}
(function() {
var extensionInstance = new ScratchSimpleGamepad(window.vm.extensionManager.runtime)
var serviceName = window.vm.extensionManager._registerInternalExtension(extensionInstance)
window.vm.extensionManager._loadedExtensions.set(extensionInstance.getInfo().id, serviceName)
})()