Skip to content

Instantly share code, notes, and snippets.

@arpruss
Created December 5, 2020 03:17
Show Gist options
  • Save arpruss/875d1530eff0b29dc73a94e97be06fd7 to your computer and use it in GitHub Desktop.
Save arpruss/875d1530eff0b29dc73a94e97be06fd7 to your computer and use it in GitHub Desktop.
class ScratchGamepad {
constructor(runtime) {
this.id = null
this.runtime = runtime
this.currentMSecs = -1
this.previousButtons = []
this.currentButtons = []
}
getInfo() {
return {
"id": "Gamepad",
"name": "Gamepad",
"blocks": [{
"opcode": "buttonPressedReleased",
"blockType": "hat",
"text": "button [b] [pr]",
"arguments": {
"b": {
"type": "number",
"defaultValue": "0"
},
"pr": {
"type": "number",
"defaultValue": "1",
"menu": "pressReleaseMenu"
},
}
}],
"menus": {
"pressReleaseMenu": [{text:"press",value:1}, {text:"release",value:0}],
}
};
}
update() {
if (this.runtime.currentMSecs == this.currentMSecs)
return
this.currentMSecs = this.runtime.currentMSecs
var gamepads = navigator.getGamepads()
if (gamepads == null || gamepads.length == 0 || gamepads[0] == null) {
this.previousButtons = []
this.currentButtons = []
this.axes = []
return
}
var gamepad = gamepads[0]
if (gamepad.id != this.id) {
this.id = gamepad.id
this.previousButtons = []
for (var i = 0; i < gamepad.buttons.length; i++)
this.previousButtons.push(false)
}
this.previousButtons = this.currentButtons
this.currentButtons = []
for (var i = 0; i < gamepad.buttons.length; i++)
this.currentButtons.push(gamepad.buttons[i].pressed)
this.axes = [];
for (var i = 0; i < gamepad.axes.length; i++)
this.axes.push(gamepad.axes[i])
}
buttonPressedReleased({b,pr}) {
this.update()
if (b < this.currentButtons.length) {
if (pr == 1) {
if (this.currentButtons[b] && ! this.previousButtons[b]) {
return true
}
}
else {
if (!this.currentButtons[b] && this.previousButtons[b]) {
return true
}
}
}
return false
}
}
window.ScratchExtensions.Gamepad = function() {return ScratchGamepad}
window.vm.extensionManager.loadExtensionURL("Gamepad");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment