造物主来到这里,一片黑暗,于是打算创建世界(场景Scene),这个世界需要灯光Light,即使世界存在,没有光线是无法看清世界的。接着需要造物者的视角,所以来个摄像机Camera模拟造物者的视角。然后创建世界的第一个物体——立方体Cube,给他上点颜色色,让他在空白的世界能够区别出来,哐哐一顿造之后,出现了一个不断翻滚的立方体。
//获取容器domconstcontainer:any=document.getElementById('three-container');//创建场景constscene=newTHREE.Scene();//创建摄像机,模拟人眼的视角constcamera=newTHREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000);camera.position.z=10;//创建渲染器constrenderer=newTHREE.WebGLRenderer();renderer.setSize(window.innerWidth,window.innerHeight);//容器中加入渲染器container.appendChild(renderer.domElement);//创建鼠标控制器constcontrols=createControls(camera,renderer)//创建光源constlight=createAmbientLight([-10,6,20])scene.add(light)scene.background=newTHREE.Color(0.9,0.9,0.9);//创建立方体constgeometry=newTHREE.BoxGeometry(1,1,1);constmaterial=newTHREE.MeshLambertMaterial({color:0x64B5D6})constcube=newTHREE.Mesh(geometry,material);scene.add(cube);//执行动画functionanimate(){requestAnimationFrame(animate);//在渲染的每一帧表更立方体的位置,达到旋转的效果cube.rotation.x+=0.01;cube.rotation.y+=0.01;renderer.render(scene,camera);}animate();创建灯光
/*创建光源*/constcreateAmbientLight=(pos:any)=>{constlightGroup=newTHREE.Group();constambientLight=newTHREE.AmbientLight(0x404040);lightGroup.add(ambientLight);constdirectionalLight=newTHREE.DirectionalLight(0xffffff,0.8);directionalLight.position.set(pos[0],pos[1],pos[2]);lightGroup.add(directionalLight);returnlightGroup;};AmbientLight是环境光,环境光会均匀的照亮场景中的所有物体。
DirectionalLight是平行光是沿着特定方向发射的光。这种光的表现像是无限远,从它发出的光线都是平行的。常常用平行光来模拟太阳光的效果。
创建鼠标控制器
import{OrbitControls}from'three/examples/jsm/controls/OrbitControls';constcreateControls=(camera:any,renderer:any)=>{constcontrols=newOrbitControls(camera,renderer.domElement);controls.enableDamping=true;controls.dampingFactor=0.25;controls.enableZoom=true;returncontrols;};Orbitcontrols是轨道控制器,可以使得相机围绕目标进行轨道运动。
造物者觉得只有一个立方体太单调了,打算创作一些东西来丰富刚刚创造的世界。于是从二维世界找了两个生物和栅栏模版,通过传送门来到3维世界,然后施加变幻魔法让2维生物变成3维生物,最后单调的世界出现了一个熊猫和两个树,还用栅栏围了起来,让这个世界变得精彩起来。