X-Git-Url: https://git.r.bdr.sh/rbdr/sumo/blobdiff_plain/7ade6f8d96825386bf2e89dea51f9297cbac8e9c..HEAD:/lib/systems/control_mapper.js?ds=sidebyside diff --git a/lib/systems/control_mapper.js b/lib/systems/control_mapper.js index e91ecc6..c0ab05e 100644 --- a/lib/systems/control_mapper.js +++ b/lib/systems/control_mapper.js @@ -2,9 +2,9 @@ import { System } from '@serpentity/serpentity'; import ControllableNode from '../nodes/controllable'; -/* global window */ - const internals = { + gamepadState: { + }, keyboardState: { } }; @@ -32,6 +32,7 @@ export default class ControlMapperSystem extends System { this.controllables = null; this._initializeKeyboard(); + this._initializeGamepad(); } /** @@ -71,11 +72,21 @@ export default class ControlMapperSystem extends System { */ update(currentFrameDuration) { + this._updateGamepads(); + for (const controllable of this.controllables) { for (const map of controllable.controlMap.map) { if (map.source.type === 'keyboard') { this._setValue(controllable.entity, map.target, !!internals.keyboardState[map.source.index]); } + + if (map.source.type === 'gamepad') { + const gamepad = internals.gamepadState[map.source.gamepadNumber]; + if (gamepad) { + const source = gamepad[map.source.gamepadInputSource]; + source && this._setValue(controllable.entity, map.target, source[map.source.index]); + } + } } } } @@ -95,6 +106,32 @@ export default class ControlMapperSystem extends System { }); } + // Requests gamepad access and binds to the events + + _initializeGamepad() { + + window.addEventListener('gamepadconnected', (event) => { + + internals.gamepadState[event.gamepad.index] = event.gamepad; + window.gamepad = event.gamepad; + }); + + window.addEventListener('gamepaddisconnected', (event) => { + + delete internals.gamepadState[event.gamepad.index]; + }); + } + + // Update Gamepad + + _updateGamepads() { + + const gamepads = navigator.getGamepads(); + for (const index of Object.keys(internals.gamepadState)) { + internals.gamepadState[index] = gamepads[index]; + } + } + // Sets the value to a target _setValue(entity, target, value) { @@ -114,5 +151,5 @@ export default class ControlMapperSystem extends System { currentObject[finalProperty] += finalValue; } } -}; +}