I did buy a cheap controller (windows thinks it's a xbox 360 controller) and I want to get some javascript keypress events from the controller. I did try some keycode testers online like http://keycode.info/ but they didn't gave something back. My question is how do i get the keycodes from the controller in javascript.
How to get the keycodes from the controller in javascript?
6.4k views Asked by Dennis AtThere are 4 answers
On
The basic Events interface does not have support for gamepads. But there is another API for that:
This is an experimental technology Check the Browser compatibility table carefully before using this in production.
HTML5 introduced many of the necessary components for rich, interactive game development. Technologies like < canvas >, WebGL, < audio >, and < video >, along with JavaScript implementations, have matured to the point where they can now support many tasks previously requiring native code. The Gamepad API is a way for developers and designers to access and use gamepads and other game controllers.
The Gamepad API introduces new events on the Window object for reading gamepad and controller (hereby referred to as gamepad) state. In addition to these events, the API also adds a
Gamepadobject, which you can use to query the state of a connected gamepad, and anavigator.getGamepads()method which you can use to get a list of gamepads known to the page.
Gamepad's key press are not handled by events. It's a Object's property stored in:
$1 an integer, from 0 to 3, so you can have up to 4 gamepads to control.
$2 an integer, from 0 to 16 in my case ;
so, we must check it by ourself.
navigator.getGamepads() returns a Gamepad List, which looks like this:
if a controller connected, it looks like this:
the first element is a Gamepad Object, it looks like this:
elements in buttons List are GamepadButton Objects, it looks like this:
if you are using Google Chome, you can check all these information by typing
navigator.getGamepads()in dev-tools( Ctrl+Shift+i to open it ) in console .if you have a gamepad in hand, you can test it use this: