web-input-system
v0.4.0
Published
Lightweight Unity-style input system for browser games: declarative input assets, three-phase action callbacks, composites, interactions & processors. Zero dependencies, engine-agnostic.
Maintainers
Readme
web-input-system
Unity Input System 的浏览器轻量版:用一份声明式输入资产(动作地图 + 动作 + 绑定) 描述全部输入,运行时得到类型安全的动作对象——回调订阅与轮询双通道,零依赖、 引擎无关(不绑定 Three.js / Phaser / React)。
特性
- 声明式输入资产:
defineInputAsset一张表声明地图/动作/绑定,动作名与值类型全推导; - 三阶段回调:
started/performed/canceled(Unity 同款生命周期),订阅返回退订函数; - 轮询双通道:
readValue()(boolean / number / Vector2)与isPressed(),地图未激活时返回默认值; - 复合绑定:
axis1D(A/D 合成轴)、vector2D(WASD 合成向量,对角线自动归一化); - Interactions:
hold(长按)/tap(点按)/doubleTap(双击)决定 button 动作何时触发; - Processors:
scale/invert/invertX/invertY/deadzone/clamp/normalize链式加工 value 动作的值(轮询与回调拿到同一加工结果); - 动作地图:
enable()/disable()显式开关 +active谓词声明式门控,二者并存; 地图失活自动给激活中的动作补发canceled(状态不卡死); - 鼠标控件:
<Mouse>/delta、<Mouse>/wheelY、<Mouse>/leftButton等内置路径, 可选指针锁定门控(gateMouseByPointerLock); - 健壮性:窗口失焦/切后台清空按键并补发
canceled、过滤 OS 按住连发(e.repeat)、 输入框/文本域打字豁免、preventDefault仅针对绑定键。
快速上手
import { createInput, defineInputAsset, vector2D, MOUSE_DELTA } from 'web-input-system';
interface Ctx { isPaused: boolean }
// 1. 输入资产:地图/动作/绑定的唯一出处(谓词参数标注类型,Ctx 由此推导)
const asset = defineInputAsset({
maps: {
gameplay: {
active: (ctx: Ctx) => !ctx.isPaused,
actions: {
move: { type: 'value', value: 'vector2', bindings: [
vector2D({ up: 'KeyW', down: 'KeyS', left: 'KeyA', right: 'KeyD' }),
]},
jump: { type: 'button', bindings: ['Space'] },
look: { type: 'value', value: 'vector2', bindings: [MOUSE_DELTA] },
},
},
ui: {
actions: {
pause: { type: 'button', bindings: ['Escape'] },
},
},
},
});
// 2. 创建管理器(上下文实时采样;也可 setContext 推送)
const input = createInput(asset, { context: () => ({ isPaused: store.paused }) });
// 3. 回调订阅(返回退订函数)
input.action('ui', 'pause').performed(() => togglePause());
input.action('gameplay', 'jump').canceled(() => console.log('jump released'));
// 4. 帧循环:轮询持续值,帧末清零增量
function frame(dt: number) {
const dir = input.action('gameplay', 'move').readValue(); // { x, y },已归一化
player.move(dir.x, dir.y);
input.update(dt);
}设计约定
Interactions(button 动作):
interactions: [hold(0.5)]决定何时触发。 默认(即press())按下即started+performed、松开canceled;hold按住满时长才performed、提前松开只canceled;tap快速点按才performed;doubleTap间隔内两次 点按才performed。计时依赖每帧调用input.update(dt);每个动作最多一个 interaction。Processors(value 动作):
processors: [scale(0.1), invertY()]在求值后按序加工, 轮询与回调拿到同一结果。每个 processor 声明自己处理的值类型(axis 走number, vector2 走vector2),不匹配的类型原样透传。增量控件(
<Mouse>/delta、MOUSE_WHEEL_Y):回调里ctx.value是本次事件的增量;readValue()轮询是本帧累计,input.update(dt)清零。只派发performed, 不维护started/canceled。离散控件(键盘/鼠标按键):
started+performed在按下时派发,canceled在松开、 失焦或所属地图失活时派发。上下文:构造选项
context: () => Ctx实时采样(推荐,无陈旧状态), 或input.setContext(ctx)推送;二者采样器优先。SSR 安全:模块顶层不触碰
window;无 DOM 环境可构造但处于未接线状态。
运行时重绑定
// 捕获流程:下一次按键/鼠标点击成为新绑定(默认 Escape 取消;失焦取消;返回函数手动取消)
input.startRebind('gameplay', 'jump', {
onComplete: (path) => console.log('jump 现在绑定到', path),
onCancel: () => console.log('已取消'),
});
// 覆盖表是纯 JSON,持久化由宿主负责
localStorage.setItem('bindings', JSON.stringify(input.exportOverrides()));
input.applyOverrides(JSON.parse(localStorage.getItem('bindings') ?? '{}'));
// 接受绑定前的冲突检测
input.findActionsByControl('Space'); // → [{ map: 'gameplay', action: 'jump' }]
// 复合绑定部件(如"向前移动"):读出、改一个部件、写回
const [wasd] = input.getBindings('movement', 'move');
input.setBindings('movement', 'move', [vector2D({ ...wasd, up: 'ArrowUp' })]);
input.resetBindings(); // 恢复资产默认