cover_photo

Start with Babylon.js & React

次世代3d web遊戲引擎學習筆記

閱讀前置準備


  1. 理解如何開始一個react app or nextjs app
  2. 理解react的component
  3. 基礎的html, css, js
  4. 會使用bun, vite等工具

專案設置步驟


Step 1 : Init project

option 1 : create nextjs app

bunx create-next-app

option 2 : create react app

bun bun create vite <app-name>

Step 2 : Install dependencies

babylonjs core

bun install @babylonjs/core

babylonjs hook

bun install babylonjs-hook

Step 3 Init Scene

create a file name src/components/CustomScene.js


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>
}

Reference


  1. Official Doc