Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Bluetooth controller in which I've tested all the numbers of the buttons with this Gamepad tester [link removed] so I'm pretty sure the values of the buttons are correct. However, nothing seems to fire, the Gamepad is shown to be "connected", just the button events not working. Below is the code:

JavaScript
function gameLoop() {
  if (navigator.webkitGetGamepads) {
    var wgp = navigator.webkitGetGamepads()[0];

    if (wgp.buttons[12] == 1 || wgp.buttons[4] == 1) {
      console.log('move');
    }
};

gameLoop();



Where could I have wrong? I'm using Chrome so I have the webkit prefix. Could the Gamepad tester be showing me the wrong buttons? Thanks for your help.

What I have tried:

I tried debugging the code but it doesn't help me.
Posted
Updated 9-Jul-23 22:48pm
v4

1)It might be a typo but the code you provided seems to be missing a closing curly brace.

2) Your code assumes the use of the 'webkitGetGamepads()' method, which is specific to webKit-based browsers. You can use the standard 'navigator.getGamepads()' method instead to give you more access to compatibility. Description and sample code is found at - Navigator: getGamepads() method[^]

3) As per OriginalGriff, you need to first check if the browser supports the 'getGamepads' method. If it does, retrieve the list of connected gamepads using 'navigator.getGamepads()'. Start by accessing the first gamepad in the list.

4) Now check if a button is pressed -
JavaScript
function gameLoop() {
  if (navigator.getGamepads) {
    var gamepads = navigator.getGamepads();
    var wgp = gamepads[0];

    if (wgp.buttons[12].pressed || wgp.buttons[4].pressed) {
      console.log('move');
    }
  }
}

gameLoop();
 
Share this answer
 
I might just add, in addition to the previous comments, from the code that I can see you're only calling the gameLoop function once? You'll need to repeatedly poll the gamepads instead, probably on a timer?

JavaScript
function gameLoop() {
  // .. code here ..
}

// poll every 10ms for updates
setInterval(() => gameLoop(), 10);
 
Share this answer
 
Comments
Andre Oosthuizen 10-Jul-23 6:28am    
Oversight from me, thanks Chris for pointing it out. Without the timer the pressed buttons will only fire once from the loop and then end. +5
You are assuming that it returns your gamepad as the first in the collection - if it isn't then your code will fail, or it won't pick up tehg buittons.

I'd start by looking at the content of the collection returned, and seeing if there are any gamepads in it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900