nx.js
Concepts

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.

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