51

GitHub - vaneenige/unswitch: ? A tiny (400b) event handler for Switch controller...

 5 years ago
source link: https://github.com/vaneenige/unswitch
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

Unswitch

npm version gzip size license dependencies

Unswitch is a tiny (400b) event handler for Switch controllers on the web based on the Gamepad API. Attach callbacks to button presses (up & down) and the joystick!

Install

$ npm install --save unswitch

Setup

Connecting a Switch controller is easy: pair it with bluetooth and you're ready to go! This library doesn't listen to connected or disconnected events but in some cases it might be useful. Here's how you can listen to these events:

window.addEventListener("gamepadconnected", ({ gamepad }) => {});
window.addEventListener("gamepaddisconnected", ({ gamepad }) => {});

Usage

// Import the library
import Unswitch from 'unswitch';

// Create the listener
const unswitch = new Unswitch({
  b: (pressed) => {},
  a: (pressed) => {},
  y: (pressed) => {},
  x: (pressed) => {},
  l: (pressed) => {},
  r: (pressed) => {},
  axes: (position) => {},
});

function render() {
  // Check for button stateupdates
  unswitch.update();
  requestAnimationFrame(render);
}

render();

Calling unswitch.update() will check every button for a change in state. If a callback is provided the new state is passed along. The axis works in the same way, but instead of a boolean it will return a number from 0 to 8. Number 0 to 7 are for the joystick positions going clockwise, number 8 is used as default (center).

Buttons are mapped based on a single controller positioned horizontally.

Contribute

Are you excited about this library and have interesting ideas on how to improve it? Please tell me or contribute directly! ?

npm install > npm run demo > http://localhost:8080

License

MIT © Colin van Eenige


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK