import { ISystem, System, Component, Components } from '../../common/engine/system'; import { IEntity, State, DoSet, DoCreate, DoDestroy } from '../../common/engine/state'; import { IGamepadSettings } from '../engine/input/devices/gamepad'; import { keyboard, gamepad, mouse } from '../engine/input/devices'; import { Asset } from '../../common/engine/asset'; let actionDispatcherData = { s: undefined }; const fireActions = (action: string, value: number, toggle: boolean) => { actionDispatcherData.s.dispatch({ type: `INPUT_${action}`, toggle, value }, false); }; interface IInputMapping { gamepad?: string; key?: string | number; type?: string; amount: number; } interface IInputActionMap { gamepadSettings: IGamepadSettings; actions: { [action: string]: IInputMapping[] }; } @Components('controller') export class Input extends System { private localPlayer: IEntity; private setupInputMappings(inputActionMap: IInputActionMap) { gamepad.setGamepadSettings(inputActionMap.gamepadSettings); for (const action in inputActionMap.actions) { if (inputActionMap.actions[action]) { for (const mapping of inputActionMap.actions[action]) { if (mapping.gamepad) { gamepad.addTemplateHandler(mapping.gamepad, (value) => { fireActions(action, mapping.amount * value, false); }); } else if (mapping.key) { switch (mapping.type) { case "RELEASED": keyboard.onKeyEvent(mapping.key, keyboard.KS_RELEASED, () => { fireActions(action, mapping.amount, false); }); break; case "PRESSED": keyboard.onKeyEvent(mapping.key, keyboard.KS_PRESSED, () => { fireActions(action, mapping.amount, false); }); break; case "TRIGGERED": keyboard.onKeyEvent(mapping.key, keyboard.KS_TRIGGERED, () => { fireActions(action, mapping.amount, false); }); break; case "TOGGLE": default: keyboard.onKeyEvent(mapping.key, keyboard.KS_PRESSED, () => { fireActions(action, mapping.amount, true); }); keyboard.onKeyEvent(mapping.key, keyboard.KS_RELEASED, () => { fireActions(action, 0, true); }); break; } } } } } } start(state: State) { super.start(state); actionDispatcherData.s = state; Asset.get('../content/systems/input.toml').then(this.setupInputMappings); } add(entity: IEntity) { super.add(entity); if (entity.controller) { if (this.localPlayer) console.log("Multiple local controllers?"); this.localPlayer = entity; } } remove(entity: IEntity) { super.remove(entity); } update(entity, component) { super.update(entity, component); } tick(delta) { } } // export const Input = { // on(actionName: string, handler: (value: number)=>void) { // if(inputActions[actionName] === undefined) inputActions[actionName] = []; // return inputActions[actionName].push(handler); // }, // off(actionName: string, handlerId: number) { // delete inputActions[actionName][handlerId]; // }, // };