Skip to content

A JavaScript library that lets you handle, configure, and use gamepads and controllers on a browser, using the Gamepad API

License

PixelRPG/gamecontroller.js

 
 

Repository files navigation

@ribajs/gameController.js

A JavaScript library that lets you handle, configure, and use gamepad and controllers on a browser.

Version 2.0.0 - Enhanced fork with improved TypeScript support, additional constants, and better controller detection.

npm npm

Getting started

@ribajs/gameController.js is a lightweight library (~9KB minified) written in TypeScript that uses the standard Gamepad API, and does not have any plugin/library dependencies.

What's New in 2.0

  • âś… Full TypeScript support with type definitions
  • âś… GAMEPAD_BUTTONS and GAMEPAD_AXES constants for W3C standard gamepad mapping
  • âś… controllerId property for automatic controller type detection
  • âś… Enhanced GamepadState interface (formerly GCGamepad)
  • âś… Improved event handling and performance
  • âś… Better browser compatibility

Installation

From npm:

npm i @ribajs/gamecontroller.js

From yarn:

yarn add @ribajs/gamecontroller.js

From pnpm:

pnpm add @ribajs/gamecontroller.js

Directly into your webpage (check latest release on github):

<script src="./gamecontroller.min.js"></script>

Usage

ES6 Modules

import { gameControl, GAMEPAD_BUTTONS, GAMEPAD_AXES } from '@ribajs/gamecontroller.js';

gameControl.on('connect', (gamepad) => {
  console.log(`Controller connected: ${gamepad.controllerId}`);
  
  // Use constants for better readability
  gamepad.before(`button${GAMEPAD_BUTTONS.BUTTON_BOTTOM}`, () => {
    console.log('A/Cross button pressed!');
  });
  
  // Or use aliases
  gamepad.on('up', moveCharacterUp);
});

CommonJS

const { gameControl, GAMEPAD_BUTTONS } = require('@ribajs/gamecontroller.js');

gameControl.on('connect', function(gamepad) {
  gamepad.on('up', moveCharacterUp);
});

Browser Script Tag

After importing the library into your webpage, gameControl will be available globally. This object comes with a series of properties and methods that will allow to handle the different gamepads connected to the computer.

The connected gamepads will be stored in a list of GamepadState objects in gameControl. This GamepadState object is not the default one returned by the browser but a higher-level interface to interact with it and simplify its usability.

gameControl.on('connect', function(gamepad) {
  gamepad.on('up', moveCharacterUp);
});

Standard Gamepad Button Constants

The library exports GAMEPAD_BUTTONS and GAMEPAD_AXES constants matching the W3C Gamepad API specification:

import { GAMEPAD_BUTTONS, GAMEPAD_AXES } from '@ribajs/gamecontroller.js';

// Button indices (0-16)
GAMEPAD_BUTTONS.BUTTON_BOTTOM      // 0 - A (Xbox) / Cross (PS)
GAMEPAD_BUTTONS.BUTTON_RIGHT       // 1 - B (Xbox) / Circle (PS)
GAMEPAD_BUTTONS.BUTTON_LEFT        // 2 - X (Xbox) / Square (PS)
GAMEPAD_BUTTONS.BUTTON_TOP         // 3 - Y (Xbox) / Triangle (PS)
GAMEPAD_BUTTONS.BUMPER_LEFT        // 4 - LB/L1
GAMEPAD_BUTTONS.BUMPER_RIGHT       // 5 - RB/R1
GAMEPAD_BUTTONS.TRIGGER_LEFT       // 6 - LT/L2
GAMEPAD_BUTTONS.TRIGGER_RIGHT      // 7 - RT/R2
GAMEPAD_BUTTONS.BUTTON_CONTROL_LEFT   // 8 - Select/Back/Share
GAMEPAD_BUTTONS.BUTTON_CONTROL_RIGHT  // 9 - Start/Menu/Options
GAMEPAD_BUTTONS.BUTTON_JOYSTICK_LEFT  // 10 - Left stick click
GAMEPAD_BUTTONS.BUTTON_JOYSTICK_RIGHT // 11 - Right stick click
GAMEPAD_BUTTONS.D_PAD_UP           // 12
GAMEPAD_BUTTONS.D_PAD_BOTTOM       // 13
GAMEPAD_BUTTONS.D_PAD_LEFT         // 14
GAMEPAD_BUTTONS.D_PAD_RIGHT        // 15
GAMEPAD_BUTTONS.BUTTON_CONTROL_MIDDLE // 16 - Home/Guide/PS button

// Axis indices (0-3)
GAMEPAD_AXES.JOYSTICK_LEFT_HORIZONTAL   // 0
GAMEPAD_AXES.JOYSTICK_LEFT_VERTICAL     // 1
GAMEPAD_AXES.JOYSTICK_RIGHT_HORIZONTAL  // 2
GAMEPAD_AXES.JOYSTICK_RIGHT_VERTICAL    // 3

Events for gameControl

For the object gameControl, events are associated using the .on() method:

gameControl.on('connect', gamepad => {
  console.log('A new gamepad was connected!');
});

Here is a list of the events that can be associated using .on():

Name Description
connect Triggered every time that a gamepad is connected to the browser. It returns an instance of the `gamepad` object described below.
disconnect Triggered when a gamepad is disconnected from the browser.
beforeCycle Triggered before the gamepads are checked for pressed buttons/joysticks movement (before those events are triggered).
afterCycle Triggered after the gamepads are checked for pressed buttons/joysticks movement (after those events have been triggered).

Events for gamepad

The events for the gamepad objects work a little bit different. The event name, is the name of the button/direction that was activated (e.g. button0, up, etc.) And there are three functions that can be used to associate event handlers for them in different situations:

  • .on(): triggered every cycle, while the button/joystick is pressed/active.
  • .before(): triggered the first cycle that a button/joystick is pressed.
  • .after(): triggered the first cycle after a button/joystick stopped being pressed.

All three functions can be chained and allow two parameters: the first one is the button/direction that was activated, and the second parameter is the callback function. Example:

gamepad.on('button0',     () => { console.log('Button 0 still pressed...'); })
       .before('button0', () => { console.log('Button 0 pressed...');       })
       .after('button0',  () => { console.log('Button 0 was released';      });

To see the event flow and how the different events are lined-up and interact with each other, check the examples in the examples/ folder.

These are the events that can be passed as first parameter to the event functions:

Name Description
button0 Triggered when button 0 is pressed.
button1 Triggered when button 1 is pressed.
button2 Triggered when button 2 is pressed.
button3 Triggered when button 3 is pressed.
button4 Triggered when button 4 is pressed.
button5 Triggered when button 5 is pressed.
button6 Triggered when button 6 is pressed.
button7 Triggered when button 7 is pressed.
button8 Triggered when button 8 is pressed.
button9 Triggered when button 9 is pressed.
button10 Triggered when button 10 is pressed.
button11 Triggered when button 11 is pressed.
button12 Triggered when button 12 is pressed.
button13 Triggered when button 13 is pressed.
button14 Triggered when button 14 is pressed.
button15 Triggered when button 15 is pressed.
button16 Triggered when button 16 is pressed.
up0 Triggered when the first axe/joystick is moved up.
down0 Triggered when the first axe/joystick is moved down.
right0 Triggered when the first axe/joystick is moved right.
left0 Triggered when the first axe/joystick is moved left.
up1 Triggered when the second axe/joystick is moved up.
down1 Triggered when the second axe/joystick is moved down.
right1 Triggered when the second axe/joystick is moved right.
left1 Triggered when the second axe/joystick is moved left.
start Triggered when Start button is pressed.
This is an alias for event button9.
select Triggered when Select button is pressed.
This is an alias for event button8.
power Triggered when Power button is pressed (e.g. the Xbox logo in an Xbox controller).
This is an alias for event button16.
l1 Triggered when the left back button 1 is pressed.
This is an alias for event button4.
l2 Triggered when left back button 2 is pressed.
This is an alias for event button6.
r1 Triggered when right back button 1 is pressed.
This is an alias for event button5.
r2 Triggered when right back button 2 is pressed.
This is an alias for event button7.
up Triggered when the main/first axe/joystick is moved up.
This is an alias for event up0.
down Triggered when the main/first axe/joystick is moved down.
This is an alias for event down0.
right Triggered when the main/first axe/joystick is moved right.
This is an alias for event right0.
left Triggered when the main/first axe/joystick is moved left.
This is an alias for event left0.

These names are not arbitrary. They match the buttons and axes described in the W3C Gamepad API specification:

Standard Gamepad Layout

TypeScript Support

The library is written in TypeScript and includes full type definitions:

import { gameControl, GamepadState, GAMEPAD_BUTTONS } from '@ribajs/gamecontroller.js';

gameControl.on('connect', (gamepad: GamepadState) => {
  // gamepad is fully typed
  console.log(`Controller: ${gamepad.controllerId}`);
  console.log(`Buttons: ${gamepad.buttons}`);
  console.log(`Axes: ${gamepad.axes}`);
  
  // Use typed constants
  gamepad.before(`button${GAMEPAD_BUTTONS.BUTTON_BOTTOM}`, () => {
    console.log('Primary action button pressed!');
  });
});

GamepadState Interface

The GamepadState interface extends the native Gamepad API with additional properties:

interface GamepadState {
  id: number;                    // Gamepad index (0, 1, 2, 3)
  controllerId: string;          // Controller ID string (e.g., "Xbox 360 Controller")
  buttons: number;               // Number of buttons
  axes: number;                  // Number of axes (joysticks * 2)
  mapping: GamepadMappingType;   // "standard" or ""
  vibration: boolean;            // Haptic feedback support
  // ... and more
}

Browser Support

Edge Logo 32x32
Edge
Firefox Logo
Firefox
Chrome
Chrome
Safari Logo
Safari
Opera logo
Opera
12+ 29+ 25+ 10.1+ 24+

Examples

The examples folder contains different examples to showcase how to use the library. To try out the examples locally run npm run serve in the root of this repository or try them now directly here:

  • Connectivity: shows how to detect if a gamepad was connected/disconnected.
  • Buttons and Joysticks: see how the buttons from your gamepad map to the default gamepad.
  • SNES Controller: replica of a SNES controller (based on a previous CodePen demo).
  • Alvanoid: small Arkanoid-based game (based on a previous CodePen demo).
  • Pong: multiplayer demo with the classic game Pong for 2 players on 2 gamepads.

Credits

This is an enhanced fork of the original gamecontroller.js by Alvaro Montoro.

Changes in this fork:

  • Full TypeScript rewrite with type definitions
  • Added GAMEPAD_BUTTONS and GAMEPAD_AXES constants
  • Added controllerId property for automatic controller detection
  • Improved event handling
  • Enhanced browser compatibility
  • Better Node.js/SSR support

About

A JavaScript library that lets you handle, configure, and use gamepads and controllers on a browser, using the Gamepad API

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 61.6%
  • JavaScript 38.4%