I'm currently working with the Gamepad API and finding it a bit challenging due to its limited development. It appears that there is no "gamepadbuttondown" event available, which can be frustrating. I came across a library called 'awesome-react-gamepads', but due to academic restrictions, I am only able to use native functionality, so I'm improvising.
To work around the lack of event capabilities, I've set up a loop to check if any button is pressed on each iteration. To prevent an infinite while
loop, I'm using requestAnimationFrame(gameLoop)
. Here's my approach:
if ("getGamepads" in navigator) {
console.log("Gamepad API is supported");
} else {
console.log("Gamepad API is not supported");
}
window.addEventListener("gamepadconnected", (e) => {
GamepadList = navigator.getGamepads()
console.log(GamepadList);
gamepad = GamepadList[0];
console.log(gamepad);
gameLoop();
});
window.addEventListener("gamepaddisconnected", (e) => {
var gamepads = navigator.getGamepads();
console.log(gamepads);
});
function gameLoop(){
const GamepadList = navigator.getGamepads();
const gamepad = GamepadList[0];
const nButtons = manette.buttons.length;
const nAxes = gamepad.axes.length;
for(let i = 0; i < nButtons; i++){
if(gamepad.buttons[i].pressed){
console.log("button pressed : ", i, "/", nButtons, "/ Value : ", gamepad.buttons[i].value);
}
}
requestAnimationFrame(gameLoop);
}
While this setup works, I noticed that every time requestAnimationFrame
calls gameLoop
, my four constants are reset. Is something off here? I tried declaring them with the let
keyword outside of everything and initializing them in the "gamepadconnected" event handler. However, I encountered a problem!
Whenever I press and release a button, the script gets stuck on that specific button, continuously logging "button pressed: 0 / 17 / Value: 1" and ignoring other buttons. I'm puzzled by this behavior and would appreciate some insight.
Thank you