From c9e358414063f8bc36afa796d781cd64299a80cf Mon Sep 17 00:00:00 2001 From: "Juan J. Martinez" Date: Mon, 10 Feb 2025 16:22:43 +0000 Subject: Controller support --- js/game.js | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/js/game.js b/js/game.js index f11174b..c2f714a 100644 --- a/js/game.js +++ b/js/game.js @@ -55,6 +55,8 @@ class Game { b: false }; + this.gamepads = {}; + this.minFps = 60; this.then = -1 / this.minFps; @@ -69,6 +71,25 @@ class Game { this.resize(); }; + window.addEventListener("gamepadconnected", (e) => { + console.log( + "Gamepad connected at index %d: %s. %d buttons, %d axes.", + e.gamepad.index, + e.gamepad.id, + e.gamepad.buttons.length, + e.gamepad.axes.length, + ); + this.gamepads[e.gamepad.index] = e.gamepad; + }); + window.addEventListener("gamepaddisconnected", (e) => { + console.log( + "Gamepad disconnected from index %d: %s", + e.gamepad.index, + e.gamepad.id, + ); + delete this.gamepads[e.gamepad.index]; + }); + this.loader(); } @@ -90,6 +111,40 @@ class Game { } loop(now) { + + Object.keys(this.gamepads).forEach((g) => { + const gp = this.gamepads[g]; + + this.keys["a"] = gp.buttons[0].pressed; + this.keys["b"] = gp.buttons[1].pressed; + + if (gp.buttons[14].pressed) { + this.keys["left"] = true; + this.keys["right"] = false; + } else { + if (gp.buttons[15].pressed) { + this.keys["left"] = false; + this.keys["right"] = true; + } else { + this.keys["left"] = false; + this.keys["right"] = false; + } + } + + if (gp.buttons[12].pressed) { + this.keys["up"] = true; + this.keys["down"] = false; + } else { + if (gp.buttons[13].pressed) { + this.keys["up"] = false; + this.keys["down"] = true; + } else { + this.keys["up"] = false; + this.keys["down"] = false; + } + } + }); + let dt = min(1000 / this.minFps, now - this.then); this._update(dt/1000); @@ -201,14 +256,14 @@ class Game { playSnd(playable, loop, clone) { if (this.playCount < this.playLimit) { - this.playCount += 1; + this.playCount++; if (clone || false) { playable = playable.cloneNode(true) } playable.onended = (ev) => { playable.onended = null; - this.playCount -= 1; + this.playCount--; }; playable.loop = loop || false; playable.play(); -- cgit v1.2.3