UNPKG

playcanvas

Version:

Open-source WebGL/WebGPU 3D engine for the web

74 lines (73 loc) 1.87 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); import { InputSource } from "../input.js"; const BUTTON_CODES = ( /** @type {const} */ { 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 { constructor() { super({ buttons: Array(BUTTON_COUNT).fill(0), leftStick: [0, 0], rightStick: [0, 0] }); /** * @type {number[]} * @private */ __publicField(this, "_buttonPrev", Array(BUTTON_COUNT).fill(0)); } /** @override */ 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(); } } /** * The button codes (based on Xbox controller layout). * * @readonly */ __publicField(GamepadSource, "buttonCode", BUTTON_CODES); export { GamepadSource };