nx.js

Controller Input

Handling user input on connected controllers

nx.js supports up to eight connected controllers. Your application can use the web Gamepad API to read the state of these controllers.

The navigator.getGamepads() function returns an array (always with a length of 8) containing either Gamepad instances, or null for indicies where the controller is not connected.

Important

Index 0 of the gamepads array is the "main" gamepad, which is a special case that reports the state of the first connected controller, as well as the handheld mode controller.

Example

Log when is pressed on the first controller:

src/main.ts
import { Button } from '@nx.js/constants';

function update() {
  requestAnimationFrame(update);

  const pads = navigator.getGamepads();
  const playerOne = pads[0];
  if (playerOne.buttons[Button.B].pressed) {
    console.log('Button "B" is being pressed on the first controller');
  }
}

update();

Tip

It is optional, but recommended to use the Button enum from the @nx.js/constants package to refer to the button indices, as shown in the example above.

Identifying controllers

Each Gamepad has an id property that identifies the controller. On Switch firmware 5.0.0 and later, this is the controller's device name plus its hardware serial number, for example:

Nintendo Switch Pro Controller (XAW10012345678)

This makes id stable and unique per physical controller, which is useful for keying per-player state or settings. The serial number is read once and cached, so reading id in your update loop is cheap. On older firmware (or if the serial is otherwise unavailable) id falls back to a per-slot string of the form switch-gamepad-<index>.

Connect and disconnect events

The global gamepadconnected and gamepaddisconnected events fire when a controller is connected to or disconnected from the system:

addEventListener('gamepadconnected', (event) => {
  console.log(`Controller connected: ${event.gamepad.id}`);
});

addEventListener('gamepaddisconnected', (event) => {
  console.log(`Controller disconnected at index ${event.gamepad.index}`);
});

Plus button behavior

By default, pressing the button on the first controller will exit the application. This is a typical convention for homebrew applications, and is also the default behavior for nx.js apps.

Preventing exit

If you would like to have different behavior for the button (for example, showing a pause screen for your game) you can call preventDefault() on the event object during the global beforeunload event:

addEventListener('beforeunload', (event) => {
  // Prevent the `+` button from exiting the application
  event.preventDefault();
});

Tip

Your application can still use the Switch.exit() function to forcefully exit the application.

On this page