Language
cover_photo

從 Babylon.js 與 React 開始

次世代 3D Web 遊戲引擎的學習筆記

Quick answer

從 Babylon.js 與 React 開始:這篇筆記整理我開始把 Babylon.js 和 React 放在一起使用的經驗。React 擅長管理 UI 與狀態,Babylon.js 則負責 3D 場景、相機、燈光、模型與渲染。

審閱狀態:可審閱後發布

這篇筆記整理我開始把 Babylon.js 和 React 放在一起使用的經驗。React 擅長管理 UI 與狀態,Babylon.js 則負責 3D 場景、相機、燈光、模型與渲染。

兩者整合時,最重要的是界線。React 不應該每次 render 都重新建立整個 3D 場景;Babylon.js 的 engine、scene 與 mesh 生命週期需要被穩定管理。

比較好的做法是讓 React 控制外層資料與 UI,並在合適的生命週期中初始化 Babylon.js。當狀態改變時,只更新必要的 scene object。

這種架構適合互動展示、3D configurator、小型遊戲原型與教育工具。它讓 3D 場景可以和一般 Web 介面共存。

建議發佈前補上最小初始化範例,以及 React component 和 Babylon scene 之間的資料流圖。

相關素材

以下整理原文中的圖片、連結、程式碼與 MDX component,作為延伸閱讀與技術參考。

連結

MDX Components

  • Interactive component unavailable: SceneComponent

程式碼與設定片段

片段 1

bunx create-next-app

片段 2

bun bun create vite <app-name>

片段 3

bun install @babylonjs/core

片段 4

bun install babylonjs-hook

片段 5


import React from "react";
import { FreeCamera, Vector3, HemisphericLight, MeshBuilder } from "@babylonjs/core";
import SceneComponent from 'babylonjs-hook';
const onSceneReady = (scene) => {
  // This creates and positions a free camera (non-mesh)
  const camera = new FreeCamera("camera1", new Vector3(0, 5, -10), scene);

  // This targets the camera to scene origin
  camera.setTarget(Vector3.Zero());

  const canvas = scene.getEngine().getRenderingCanvas();

  // This attaches the camera to the canvas
  camera.attachControl(canvas, true);

  // This creates a light, aiming 0,1,0 - to the sky (non-mesh)
  const light = new HemisphericLight("light", new Vector3(0, 1, 0), scene);

  // Default intensity is 1. Let's dim the light a small amount
  light.intensity = 0.7;

  // Our built-in 'box' shape.
  box = MeshBuilder.CreateBox("box", { size: 2 }, scene);

  // Move the box upward 1/2 its height
  box.position.y = 1;

  // Our built-in 'ground' shape.
  MeshBuilder.CreateGround("ground", { width: 6, height: 6 }, scene);
};

/**
 * Will run on every frame render.  We are spinning the box on y-axis.
 */
const onRender = (scene) => {
  if (box !== undefined) {
    const deltaTimeInMillis = scene.getEngine().getDeltaTime();

    const rpm = 10;
    box.rotation.y += (rpm / 60) * Math.PI * 2 * (deltaTimeInMillis / 1000);
  }
};
export default function CustomScene(){
  return <div> 
    <SceneComponent /> 
  </div>
}

FAQ

這篇文章主要在介紹什麼?

這篇筆記整理我開始把 Babylon.js 和 React 放在一起使用的經驗。React 擅長管理 UI 與狀態,Babylon.js 則負責 3D 場景、相機、燈光、模型與渲染。

這篇文章適合誰閱讀?

適合想理解 從 Babylon.js 與 React 開始 背後實作、設計取捨與學習脈絡的讀者。

Buy me a coffee