编程

Babylon.js 简介

1744 2023-05-26 23:27:00

babylonjs 是一款强大、漂亮、简单、开放的游戏和渲染引擎,以 Javascript 框架发布。

npm

BabylonJS 及其模块发布在npm上,并提供全类型支持。使用下面命令安装: 

npm install babylonjs --save

或者,您现在可以依赖 ES6 软件包。使用 ES6 版本将允许树抖动以及其他捆绑好处。

引入整个包:

import * as BABYLON from 'babylonjs';

或者单独引入类:

import { Scene, Engine } from 'babylonjs';

如果使用了 TypeScript,别忘了添加 'babylonjs' 到 tsconfig.json 的 'types'  中:

    ...
    "types": [
        "babylonjs",
        "anotherAwesomeDependency"
    ],
    ...

要添加模块,请安装相应的软件包。可以在 npm 上的 babylonjs 用户中找到额外软件包的列表及其安装说明。

用例

// Get the canvas DOM element
var canvas = document.getElementById('renderCanvas');
// Load the 3D engine
var engine = new BABYLON.Engine(canvas, true, {preserveDrawingBuffer: true, stencil: true});
// CreateScene function that creates and return the scene
var createScene = function(){
    // Create a basic BJS Scene object
    var scene = new BABYLON.Scene(engine);
    // Create a FreeCamera, and set its position to {x: 0, y: 5, z: -10}
    var camera = new BABYLON.FreeCamera('camera1', new BABYLON.Vector3(0, 5, -10), scene);
    // Target the camera to scene origin
    camera.setTarget(BABYLON.Vector3.Zero());
    // Attach the camera to the canvas
    camera.attachControl(canvas, false);
    // Create a basic light, aiming 0, 1, 0 - meaning, to the sky
    var light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), scene);
    // Create a built-in "sphere" shape using the SphereBuilder
    var sphere = BABYLON.MeshBuilder.CreateSphere('sphere1', {segments: 16, diameter: 2, sideOrientation: BABYLON.Mesh.FRONTSIDE}, scene);
    // Move the sphere upward 1/2 of its height
    sphere.position.y = 1;
    // Create a built-in "ground" shape;
    var ground = BABYLON.MeshBuilder.CreateGround("ground1", { width: 6, height: 6, subdivisions: 2, updatable: false }, scene);
    // Return the created scene
    return scene;
}
// call the createScene function
var scene = createScene();
// run the render loop
engine.runRenderLoop(function(){
    scene.render();
});
// the canvas/window resize event handler
window.addEventListener('resize', function(){
    engine.resize();
});