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());
相关推荐
ganshenml17 小时前
sed 流编辑器在前端部署中的作用
前端·编辑器
sulikey21 小时前
从入门到精通:如何自己编写高质量的 .gitignore(面向工程实践)
git·gitee·编辑器·gitlab·github·gitignore·gitattributes
EQ-雪梨蛋花汤1 天前
【AI工具】使用 Doubao-Seed-Code 优化 Unity 编辑器插件:从功能实现到界面美化的完整实践
人工智能·unity·编辑器
allenjiao1 天前
WebGPU vs WebGL:WebGPU什么时候能完全替代WebGL?Web 图形渲染的迭代与未来
前端·图形渲染·webgl·threejs·cesium·webgpu·babylonjs
0欧姆1 天前
VScode 创建 QNX 模板工程
ide·vscode·编辑器
dyxal2 天前
Vim插件深度探索:打造终极开发环境
linux·编辑器·vim
凌晨一点的秃头猪2 天前
VScode 添加远程服务器教程
ide·vscode·编辑器
Hi_kenyon2 天前
使用vim来完全控制你的VSCode(一)
vscode·编辑器·vim
q***06293 天前
Node.js使用教程
node.js·编辑器·vim
zyplayer-doc3 天前
目录支持批量操作,文档增加可见范围、锁定功能,PDF查看优化,zyplayer-doc 2.5.8 发布啦!
数据库·人工智能·pdf·编辑器·飞书·石墨文档