Browse Source

add basic keyboard controls

main
Colin McMillen 5 years ago
parent
commit
822a5a108e
  1. 59
      main.js

59
main.js

@ -5,12 +5,18 @@ const Orientation = {
RIGHT: 'right'
}
// TODO: make these not global.
let upArrowPressed = false;
let downArrowPressed = false;
let leftArrowPressed = false;
let rightArrowPressed = false;
class Input {
constructor() {
this.left = false;
this.right = false;
this.up = false;
this.down = false;
this.left = false;
this.right = false;
this.a = false;
this.b = false;
this.x = false;
@ -20,25 +26,60 @@ class Input {
this.select = false;
this.start = false;
this.leftArrowPressed = false;
this.rightArrowPressed = false;
window.addEventListener('gamepadconnected', this.gamepadConnected);
window.addEventListener('gamepaddisconnected', this.gamepadDisconnected);
document.addEventListener('keydown', this.keyDown);
document.addEventListener('keyup', this.keyUp);
}
keyDown(e) {
if (e.key == 'ArrowUp' || e.key == 'w') {
upArrowPressed = true;
}
if (e.key == 'ArrowDown' || e.key == 's') {
downArrowPressed = true;
}
if (e.key == 'ArrowLeft' || e.key == 'a') {
leftArrowPressed = true;
}
if (e.key == 'ArrowRight' || e.key == 'd') {
rightArrowPressed = true;
}
}
keyUp(e) {
if (e.key == 'ArrowUp' || e.key == 'w') {
upArrowPressed = false;
}
if (e.key == 'ArrowDown' || e.key == 's') {
downArrowPressed = false;
}
if (e.key == 'ArrowLeft' || e.key == 'a') {
leftArrowPressed = false;
}
if (e.key == 'ArrowRight' || e.key == 'd') {
rightArrowPressed = false;
}
}
update() {
// TODO: have a config screen instead of hard-coding the 8Bitdo SNES30 pad.
// TODO: handle connects / disconnects more correctly.
this.up = upArrowPressed;
this.down = downArrowPressed;
this.left = leftArrowPressed;
this.right = rightArrowPressed;
const gamepad = navigator.getGamepads()[0];
if (gamepad == null || !gamepad.connected || gamepad.axes.length < 2 ||
gamepad.buttons.length < 12) {
return;
}
this.left = gamepad.axes[0] < 0;
this.right = gamepad.axes[0] > 0;
this.up = gamepad.axes[1] < 0;
this.down = gamepad.axes[1] > 0;
this.up |= gamepad.axes[1] < 0;
this.down |= gamepad.axes[1] > 0;
this.left |= gamepad.axes[0] < 0;
this.right |= gamepad.axes[0] > 0;
this.a = gamepad.buttons[0].pressed;
this.b = gamepad.buttons[1].pressed;
this.x = gamepad.buttons[3].pressed;

Loading…
Cancel
Save