How to use JavaScript Gamepad API to Build a Simple Game



In this exciting tutorial we will use the JavaScript Gamepad API to build a simple game to move a player around on the screen using a game controller.

We will be programming the direction pad and left analog stick to move the player on the screen. We will also use the face buttons to change the color of the player depending on the button pressed.

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.

GItHub
https://github.com/CodingWith-Adam/gamepad-api-simple-game

Try the game here:
https://codingwith-adam.github.io/gamepad-api-simple-game/

Gamepad Tester
https://codingwith-adam.github.io/gamepad-tester/

Build a Gamepad tester Tutorial
https://youtu.be/tQyrpcOK6U0

Gamepad API MDN
https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API

Chapters
00:00 intro
00:15 Project Overview
00:53 Project setup
3:00 JS Game setup
4:32 Setup Canvas
5:16 Resize Canvas
6:46 Game Loop
7:21 Clear Screen
8:14 Draw player
9:08 Handle Input Boilerplate code
9:45 Gamepad API Overview
10:04 Gamepad API connect disconnect.
11:41 Controller input function and Gamepad object review
13:52 Controller Direction pad
14:54 update player – move player
17:05 Controller Stick to move player
19:47 Change player color with face buttons

Comments are closed.