UNPKG

playcanvas

Version:

PlayCanvas WebGL game engine

71 lines (68 loc) 1.42 kB
import { InputSource } from '../input.js'; const BUTTON_CODES = { A: 0, B: 1, X: 2, Y: 3, LB: 4, RB: 5, LT: 6, RT: 7, SELECT: 8, START: 9, LEFT_STICK: 10, RIGHT_STICK: 11 }; const BUTTON_COUNT = Object.keys(BUTTON_CODES).length; class GamepadSource extends InputSource { static{ this.buttonCode = BUTTON_CODES; } constructor(){ super({ buttons: Array(BUTTON_COUNT).fill(0), leftStick: [ 0, 0 ], rightStick: [ 0, 0 ] }), this._buttonPrev = Array(BUTTON_COUNT).fill(0); } read() { const gamepads = navigator.getGamepads(); for(let i = 0; i < gamepads.length; i++){ const gp = gamepads[i]; if (!gp) { continue; } if (gp.mapping !== 'standard') { continue; } if (gp.axes.length < 4) { continue; } if (gp.buttons.length < BUTTON_COUNT) { continue; } const { buttons, axes } = gp; for(let j = 0; j < this._buttonPrev.length; j++){ const state = +buttons[j].pressed; this.deltas.buttons[j] = state - this._buttonPrev[j]; this._buttonPrev[j] = state; } this.deltas.leftStick.append([ axes[0], axes[1] ]); this.deltas.rightStick.append([ axes[2], axes[3] ]); } return super.read(); } } export { GamepadSource };