0

I'm writing a little javascript game and trying to make it work with a gamepad. The gamepad works (on linux at least). I wrote this code:

var gamePad;
var checkForGamepad;

function startPolling() {
checkForGamepad= setInterval(function () {
gamePad= navigator.webkitGetGamepads && navigator.webkitGetGamepads()[0]
},20)}

function stopPolling(){
 clearInterval(checkForGamepad);
 checkForGamepad=null;
}

This is for starting to check if there is a gamecontroller connected and I can also stop it (for when I'm in the menu for example). But now I want to write an event recorder. I wrote already one for the keyboard, but that's easy because you have a 'keyup' event. Does anybody have an idea, how to write an event recorder for a gamepad?

My event recorder for my keyboard looks like this:

function gameNavigationKey(evt){
switch (evt.keyCode){
case 32:  // spacebar was pressed 
//change the gravity
// do some other stuff
break;
.
.
.
}

And in the code when I start my gameloop(), I also call window.addEventListener('keyup',gameNavigationKey,true)

So I want basically the same style for my event recorder with my gamepad. I know I can read values of keys being pressed on the gamepad using gamePad.buttons[0] returns 0 when not pressed 1 while being pressed. So I think I need to remember the previous state of my key, but still, don't have an idea how to start. Can somebody please help me creating this event recorder? Thanks in advance

Bosiwow
  • 2,025
  • 3
  • 28
  • 46
  • Do you get `keyup` and `keydown` events for the gamepad keys? If so, just keep a list of all gamepad keys and whether they are pressed or not. Then have a separate loop poll that list to see what action to take. – Halcyon Oct 22 '13 at 12:04
  • I tried it, but it didn't work :s – Bosiwow Oct 22 '13 at 12:16

1 Answers1

1

In the current implementation of the Gamepads with Chrome, at every update you have to call:

 navigator.webkitGetGamepads();

It will give you the latest status of the pads. If you want to implement something out of it you will need to compare with the previous status and make your own events.

Firefox doesn't require to call getGamepads at every frame, but updates the object automatically after you implement the events gamepadconnected and gamepaddisconnected.

You can find extra information here:

http://www.html5rocks.com/en/tutorials/doodles/gamepad/ https://developer.mozilla.org/en-US/docs/Web/Guide/API/Gamepad

RRoquais
  • 91
  • 5