diff options
author | Juan J. Martinez <jjm@usebox.net> | 2025-02-10 16:22:43 +0000 |
---|---|---|
committer | Juan J. Martinez <jjm@usebox.net> | 2025-02-10 16:22:43 +0000 |
commit | c9e358414063f8bc36afa796d781cd64299a80cf (patch) | |
tree | 623db8e5c79da59d9bd3d7678fa23e6fa045653a | |
parent | ab117a96bd868dc211eb091272f8549be1b0da86 (diff) | |
download | js-canvas-2023-c9e358414063f8bc36afa796d781cd64299a80cf.tar.gz js-canvas-2023-c9e358414063f8bc36afa796d781cd64299a80cf.zip |
Controller support
-rw-r--r-- | js/game.js | 59 |
1 files changed, 57 insertions, 2 deletions
@@ -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(); |