ctx.input 管理扩展输入。长期功能优先使用“注册语义动作 + 订阅动作”,短生命周期的临时按键才使用 bindShortcut()。
API
| 方法 | 返回值 | 说明 |
|---|
bindShortcut(shortcut, handler) | 解绑函数 | 直接绑定一个物理快捷键 |
registerAction(action) | void | 注册可在 Studio 中重映射的语义动作 |
unregisterAction(id) | void | 反注册动作并移除其订阅和玩家覆盖 |
onAction(id, handler) | 取消订阅函数 | 监听动作触发 |
listActions() | ActionInfo[] | 列出已注册动作 |
getActiveKeys(id) | string[] | 获取动作当前生效的物理键 |
扩展动作 id 必须以当前扩展 id 为前缀,且不能使用引擎保留的 internal.* 前缀。
案例:注册“打开任务面板”动作
输入: 当前扩展 id 是 user.quest-panel,默认希望玩家按 Q 打开 quest-panel。
static onRegister(ctx) {
const actionId = "user.quest-panel.open";
ctx.input.registerAction({
id: actionId,
label: "打开任务面板",
defaultKeys: ["KeyQ"],
});
ctx.input.onAction(actionId, () => {
void ctx.ui.show("quest-panel");
});
console.log(ctx.input.getActiveKeys(actionId));
}
输出:
“打开任务面板”会出现在 Studio 的输入按键设置中。玩家按当前生效键时,quest-panel 被打开;如果玩家把动作改为 F2,getActiveKeys() 会改为输出 ["F2"],业务代码无需修改。
bindShortcut("Escape", handler) 适合只在某个模态界面打开期间生效的临时绑定。记得在界面关闭时调用它返回的解绑函数。