Gamepad interference causing obstruction of `requestAnimationFrame()`

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

Answer №1

It appears there is a little issue here, as manette is not defined:

    const nButtons = manette.buttons.length;

To address this problem, I have created a demonstration on how you can create your own custom events for gamepad buttons and axes:

https://github.com/nondebug/gamepad-event-source/blob/main/index.html

The developers working on the Gamepad API specification have been looking to include gamepad input events, as discussed in this link. I presented a proposal here, although it has yet to be accepted or incorporated into any web browsers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoking one service from another service in AngularJS

I'm trying to access a service from another service and use the returned object for some operations. However, I keep encountering a TypeError: getDefinitions is not a function error. Here is the code for my services and controller: definitions.servi ...

Looking for the function to activate when the enter key is pressed

I have a search box which is a text type and has a click button that initiates the Find() function. How can I enable searching by pressing Enter inside the textbox? ...

Execution of Ajax call fails to occur synchronously

I have created a unique weather website that utilizes the flickr API as well as the yahoo API to gather weather data. However, I am facing an issue where the ajax call from the yahoo API does not retrieve the necessary data in time for the content of the p ...

Choosing to maintain an open server connection instead of regularly requesting updates

Currently, I am in the process of developing an innovative online presentation tool. Let's dive into a hypothetical situation: Imagine one person is presenting while another connects to view this presentation. >> How can we ensure that the vie ...

Tips on transferring information from AngularJS to a remote server using ngResource

Looking for guidance on utilizing the ngResource module? To send data to a server. To retrieve data from a server. I am attempting to send data to a Solr server. Utilizing AngularJS API. Using npm package manager to install packages to my application. Th ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

Detection of NTLM error during the parsing of the Authorization header

After posting a question here, I discovered that the issue causing the error was not related to my axios request. Unfortunately, I'm unsure how to close the question. An error occurs when attempting to send an Axios Get request to my express backend ...

There was an error in the search: [parse_exception] The search source could not be parsed. A field name was expected, but instead [

I'm experiencing a query parsing exception while utilizing JavaScript for Elasticsearch configuration found in elastic.js file. Results are obtained when the filtered part is removed. However, upon adding it back, an exception occurs. var client = r ...

Substitute the specific class title with the present class

Here is a sample class (supposed to be immutable): class A { normalMethod1(): A{ const instance = this.staticMethod1(); return instance; } static staticMethod1: A(){ return new this(); } } The code above works fine, but how can I re ...

Preserving the true IP address when initiating cross-domain requests

Initially, I tried creating a reverse proxy using Express to enable forwarding requests from localhost:3000/request to somesite.com/request. Here is the code snippet I used: var request = require('request'); app.get('/', function(req, ...

Creating a multipart/form-data request using JavaScript/jQuery

After much searching and experimentation, I have been trying to understand the process of constructing a request to be sent using something similar to $.ajax({ contentType: "multipart/form-data", type: "POST", data: ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

Transfer files using Ajax and FormData technique

I have extensively researched various topics on this issue and prefer not to rely on any external plugins. function addToDatabase(menuItem){ var formData = new FormData(); formData.append("Description", document.getElementById("DescriptionID").value); ...

Tips on how to update a table following each button click during an ajax request

I am encountering an issue while trying to display data in a table by clicking on a search button. The problem arises when there is no data between the specified "Fromdate - Todate" range; the error message appears correctly. However, even after entering t ...

Showcase big image upon hovering mouse with automatic positioning on Magento

As a newcomer to magento, I am interested in adding an effect that displays a large image when hovering over it with the mouse. This feature should automatically position itself on the product listing page in magento. Your assistance is greatly appreciate ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

How to modify browser's back button action in Vue.js

Is there a way to detect the back function in the browser and then redirect to a different page using Vue.js? Here's what I've tried so far. mounted: function () { window.onpopstate = function(event) { this.$router.push({ path: ...

Using AJAX in a WordPress template

I'm currently facing an issue with integrating my operational php/javascript/ajax application into my WordPress theme. This application is meant for my users and not within the admin panel. Steps I've taken: I have successfully included the Java ...

Are the JQuery appended elements exceeding the width of the parent div?

I have an HTML div that is styled using the Bootstrap class span9. <div class="span9"> <div id = "selectedtags" class="well"> </div> <button class="btn" type="button" id="delegatecontent">Generate report</button&g ...

Error message indicating a problem with the locator By.linkText that contains dots in Selenium: TypeError - Invalid locator

I've searched through other resources for solutions, but I can't find anything that addresses my specific issue. The error message I'm encountering is TypeError: Invalid locator. Here's a snippet of my code (where I suspect the problem ...