Babylon 编辑器快捷键小记

一、最终代码(带满屏注释)

TypeScript 复制代码
// Babylon.js 键盘事件枚举
import { KeyboardEventTypes } from "@babylonjs/core";
// 全局事件总线(mitt)
import { emitter } from "../../utils/EventBus";
// 编辑器系统,内部有 keyboardController
import type { EditorSystem } from "../EditorSystem";

/**
 * 快捷键管理器
 * 职责:
 * 1. 监听键盘事件
 * 2. 根据规则分发事件到 EventBus
 * 3. 支持单键 & Ctrl+? 组合键
 */
export class ShortCutsManager {
  // 编辑器引用,主要用来拿 keyboardController
  private _editorSystem: EditorSystem;

  /**
   * 单键映射
   * key -> EventName
   */
  private _shortcutDictionary: ShortcutDictionary = {
    q: "selectMode",
    w: "moveMode",
    e: "rotateMode",
    r: "scaleMode",
    delete: "openDeleteConfirm"
  };

  /**
   * Ctrl+? 组合键映射
   * 仅记录"字母部分",判断时再加前缀 "Control"
   */
  private _ctrlShortcutDictionary: ShortcutDictionary = {
    s: "saveScene", // Ctrl+S
    o: "openScene", // Ctrl+O
    n: "newScene",  // Ctrl+N
    z: "undo",      // Ctrl+Z
    y: "redo"       // Ctrl+Y
  };

  constructor(editorSystem: EditorSystem) {
    this._editorSystem = editorSystem;
    this._init();
  }

  /** 初始化:注册键盘事件 */
  private _init(): void {
    const keyboardController = this._editorSystem.keyboardController;
    if (!keyboardController) {
      console.error("GlobalKeyboardController is not initialized.");
      return;
    }

    // 监听所有 KEYDOWN 事件
    keyboardController.addListener(KeyboardEventTypes.KEYDOWN, () => {
      // 当前按下的单个字符(已转成小写)
      const onlyKey = keyboardController.pressedSingleNormalKey?.trim().toLowerCase();
      if (!onlyKey) return; // 没按字符键直接返回

      // ---------- 组合键优先 ----------
      if (keyboardController.isModifierKeysCombined(["Control"])) {
        const eventName = this._ctrlShortcutDictionary[onlyKey];
        if (eventName) {
          emitter.emit(eventName);
          return; // 命中组合键后不再走单键
        }
      }

      // ---------- 单键 ----------
      const eventName = this._shortcutDictionary[onlyKey];
      if (eventName) {
        emitter.emit(eventName);
      }
    });
  }
}

/** 字典类型:string -> string */
interface ShortcutDictionary {
  [key: string]: string;
}

二、怎么用

任意地方监听

TypeScript 复制代码
import { emitter } from '@/utils/EventBus';

emitter.on('undo', () => console.log('撤销'));
emitter.on('saveScene', () => scene.save());
相关推荐
zyplayer-doc16 小时前
知识库新增三方应用AI问答,新增标签管理,集成Excalidraw,重构全文检索,zyplayer-doc 2.5.4 发布啦!
人工智能·编辑器·全文检索·飞书·企业微信·开源软件·有道云笔记
coding-fun17 小时前
SuperScript:C#脚本编辑器、C#脚本引擎
开发语言·c#·编辑器
liu_endong20 小时前
vscode关闭coplit功能
ide·vscode·编辑器
背太阳的牧羊人20 小时前
vscode在断点旁边写expression让条件为true的时候才触发断点提高调试效率
ide·vscode·编辑器
我是苏苏20 小时前
Linux02: 编辑器nano的常用技巧
编辑器
CC.GG1 天前
【Linux】Linux编辑器--vim
linux·编辑器·vim
Laughtin1 天前
dolphindb vscode更改连接配置的操作步骤
ide·vscode·编辑器
陈言必行9 天前
Unity 性能优化 之 编辑器创建资源优化( 工作流 | 场景 | 预制体)
unity·编辑器·游戏引擎
CAE虚拟与现实10 天前
VSCode中的下载VSIX是指什么?
ide·vscode·编辑器
CAE虚拟与现实10 天前
VSCode官方汉化包
ide·vscode·编辑器·vscode汉化