HTML and CSS Reference
In-Depth Information
Here's the code to manage the state of a disconnecting a device:
window.addEventListener("gamepaddisconnected", function(e) {
delete gamepadAPI.controllers[e.gamepad.index];
if(!gamepadAPI.controllers.length) {
gamepadAPI.active = false;
}
console.log('Gamepad disconnected.');
});
You're adding an event listener to the event named gamepaddisconnected . Thanks to this step, when the device is
no longer available, you will delete the row containing your gamepad object with all of its data. If this was the last available
device, you will also set the active variable to false . You can do other things here, or just use the gamepadAPI.active
variable anywhere in your code to control the game depending on whether the device is connected or not.
Detecting Button Presses
To know what button was pressed, you can listen for a particular event: gamepadbuttondown . This will provide the
information that you want.
window.addEventListener("gamepadbuttondown", function(e) {
gamepadAPI.buttonPressed(e);
});
If you define a function called buttonPressed , you can see which button was pressed.
buttonPressed: function(event) {
var button = event.button;
console.log("Button "+button+" was pressed.");
}
There's also the gamepadbuttonup event, which tells you that the given button was released. You can change the
buttonPressed function to reflect that and then fire at those two events.
buttonPressed: function(event, pressed) {
var button = event.button;
if(pressed) {
console.log("Button "+button+" was pressed.");
}
else {
console.log("Button "+button+" was released.");
}
}
Now all you have to do is to bind this function to those two events.
window.addEventListener("gamepadbuttondown", function(e) {
gamepadAPI.buttonPressed(e, true);
});
window.addEventListener("gamepadbuttonup", function(e) {
gamepadAPI.buttonPressed(e, false);
});
 
Search WWH ::




Custom Search