Check out a free preview of the full A Tour of Web Capabilities course:
The "Gamepad API" Lesson is part of the full, A Tour of Web Capabilities course featured in this preview video. Here's what you'd learn in this lesson:

Max introduces the Gamepad API. It works with both USB and Bluetooth controllers. Since the buttons and controls vary greatly across controllers, a game loop must be created using requestAnimationFrame to watch for input and determine which button was pressed.

Get Unlimited Access Now

Transcript from the "Gamepad API" Lesson

>> Gamepad API. I have a Gamepad API here with me. And this is the time where we're going to start working with our project, with the Gamepad API. So this is a green light API, green. It works everywhere, which is cool. So, the Gamepad API will let you connect and use a gamepad.

[00:00:23] Any gamepad will work, if it's using the gamepad interface with the OS. It can be USB or it can be connected through Bluetooth. It works. And it's a high-level API. Which means that I don't need to know the specifics of this gamepad to actually work with it. It's a gamepad, so I know it will have buttons, and it will have axes.

[00:00:50] That's all I need to know. And then I can use the gamepad. So this is of course cool for games. It's low latency. It depends on the frequency that you want, but for standard situations is low latency. Actually, how to use that, it's not what you're expecting. It happened to me the first time I used the API.

[00:01:14] So I have a gamepad, the gamepad has buttons, right? So you say, okay, I wanna take the click of one button, like mouse. That's not how that works. So actually what you need to do is you create a game loop with request animation frame. That's a way to execute a timer on every frame on the animation that you have on a game.

[00:01:39] Even if you don't have a game, it doesn't matter. And you need to check the status of the gamepad all the time. And you will get a boolean if one key is pressed. So I will get the boolean. The problem is that I need to save that somewhere.

[00:01:57] And if I keep my finger pressed. Of course, I'm keeping true for several seconds. So if you fire the click handler, when you see a true you will have a problem because you will fire that 100 times. So requestAnimationFrame can be 60 frames per second, 30 frames per second, depends on the device.

[00:02:20] So you might be triggering that event handler 30 or 60 times. So we need to trick it a little bit. I will show you how I did that with our project in a second. And the same happens with the axis. You will get actually four axes, because you have in this case two, and then X and Y on each.

[00:02:44] And you get a value from -1 to 1, depends on where you are. It's a float value.