DEV Community

Cover image for How to use JS Gamepad API and Build a Gamepad Tester

Posted on

How to use JS Gamepad API and Build a Gamepad Tester

In this exciting tutorial we are going to learn how to use the JavaScript Gamepad API. With this API we are going to build our very own gamepad tester. A gamepad tester allows you to diagnose and figure out if anything is wrong with your controller. The video tutorial uses Javascript HTML and CSS to build a Gamepad tester.

Try out the final product here:


Project Description

This project has two parts: a grid that displays all the controller buttons and an awesome picture of a controller. As buttons are pressed you can see them turn red on the controller. When the analog sticks are moved the position is displayed on the controller image in real time. Above the controller we have a diagnostic grid that displays the values of all buttons and axes in real time.

As you may know most controllers have pressure sensitive triggers. In the controller image we tweak the contrast to show much how much pressure is being placed on the trigger. In the diagnostics grid we not only display the value but a vertical meter to show how much of the trigger is being pressed.

With the JS Gamepad API we can even make the controller rumble. In our gampad tester we create a toggle checkbox to cause the controller to rumble with each button press.

Even though we have a PS4 Controller in the picture this image will work for Xbox and even the Nintendo Switch Pro controller.

What is the JavaScript Gamepad API?

The JS Gamepad API allows developers to use a gamepad as an input device. The most common usage would be for game development. The Gamepad API has 2 events. One event for when a controller is connected and another for when it is disconnected. There is no event for when a button is pressed on the controller. However the developer can ask the Gamepad for the state of the buttons at any time. Included in this state is the list of buttons and a list of axes that represent the analog sticks if there are any. Checking for the controller state can be done in a loop or on a timer. For game development this will happen in the game loop. At the start of each game loop you can retrieve the state of the buttons and then use that information to manipulate your game.

The Gamepad API also includes experimental features like rumbling the controller and retrieving the position of the controller in virtual reality when using WebVR.

All of these features can be combined together to build a gamepad tester. Check out the tutorial to learn more:

Top comments (0)