先来认识一下Babylonjs,由于基于webgl来开发,所以先介绍一下基础知识。
Webgl是一个html标准,他要在canvas元素上初始化。
Html页面上的准备
所以我们先从html页面开始看起
我们设置一个canvas,提供给babylon渲染用
然后因为我们用typescript,你可以看到引入的脚本叫app.js,但是在我么的项目里只有app.ts
生成的时候app.ts 会被编译为app.js
TypeScript代码
看,熟悉的class,比js的prototype看着舒服吧,看()=> 熟悉的"辣么大"表达式。
这段代码很好理解吧,window.onload 是页面初始化事件,在这里取得canvas,并用它初始化了Game
Game是我弄了个当主程序的东西,使用咱客户端过去的习惯。
Update 和 stop 其实都没写
Int里面初始化了 babylon engine
创建了一个场景,然后告诉babylonengine 开始渲染,渲染方法就是调用scene.render();
看看createScene函数都干了什么
这地方api设计有一点混乱,engine初始化就妖了canvas
Camera又要和canvas关联
这是先初始化场景、摄像机、灯光
// create a basic BJS Scene object
var scene = new BABYLON.Scene(this.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(this.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; its constructor takes 5 params: name, width, depth, subdivisions, scene
var sphere = BABYLON.Mesh.CreateSphere(‘sphere1‘, 16, 2, scene);
// move the sphere upward 1/2 of its height
sphere.position.y = 1;
// create a built-in "ground" shape; its constructor takes the same 5 params as the sphere‘s one
var ground = BABYLON.Mesh.CreateGround(‘ground1‘, 6, 6, 2, scene);
一个球,一个平面
Babylon 为你准备了大量的基本形体
var box = BABYLON.Mesh.CreateBox("box", 1.0, scene);
box.position = new BABYLON.Vector3(3, 0, 0);
var plane = BABYLON.Mesh.CreatePlane("plane", 2.0, scene);
plane.position = new BABYLON.Vector3(2, 0, 1);
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 3, 3, 3, 6, 1, scene, false);
cylinder.position = new BABYLON.Vector3(-2, 0, 1);
var torus = BABYLON.Mesh.CreateTorus("torus", 5, 1, 10, scene, false);
torus.position = new BABYLON.Vector3(-3, 0, 1);
var knot = BABYLON.Mesh.CreateTorusKnot("knot", 2, 0.5, 128, 64, 2, 3, scene);
knot.position.y = 3;
var lines = BABYLON.Mesh.CreateLines("lines", [
new BABYLON.Vector3(-10, 0, 0),
new BABYLON.Vector3(10, 0, 0),
new BABYLON.Vector3(0, 0, -10),
new BABYLON.Vector3(0, 0, 10)
], scene);
我们随便建立一批
这就是babylon引擎的基本初始化和形体