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());
相关推荐
史丹利复合田14 小时前
【无标题】vscode远程连接,服务器端配置
ide·vscode·编辑器
wtsolutions16 小时前
图片GPS数据编辑器批量处理功能详解 - 高效管理大量图片的位置信息
编辑器·gps·图片·照片
cooldream200916 小时前
Vim 报错 E325:swap 文件冲突的原理、处理流程与彻底避免方案
linux·编辑器·vim
wtsolutions18 小时前
如何用图片GPS数据编辑器解决批量图片位置信息管理问题
编辑器·gps·图片·照片
山峰哥19 小时前
SQL调优实战密码:索引策略与Explain工具深度破局之道
java·开发语言·数据库·sql·编辑器·深度优先
AI分享66621 小时前
VSCode如何使用claude code(VS Code + Claude API 详细教程)(API 配置图文全攻略)
ide·vscode·编辑器
森叶1 天前
Node.js 跨进程通信(IPC)深度进阶:从“杀人”的 kill 到真正的信号
node.js·编辑器·vim
中科院提名者1 天前
如何修改VScode里的注释
ide·vscode·编辑器
艾莉丝努力练剑1 天前
人工智能 Gemini 2.5 Pro:深度解析技术突破与实战应用
c++·人工智能·python·ai·大模型·编辑器·gemini
史丹利复合田2 天前
如何使用vscode进行Python远程调试(支持带参数调试)
ide·vscode·编辑器