第二章
创建中的基本组件:
1.相机
2.光源
3.物体
创建渲染的时候,相机会自动加载到场景中。当然啦,你也可以手动添加。
相机,光源等,只要添加到场景中都算是物体。
scene.add(obj);
scene.children 数组,元素是obj
obj instanceof THREE.MESH 当然还有光源和相机
Scene.getChildByName(name)
scene.remove(obj);
物体的属性:
name 唯一标识物体
遍历场景中的物体:
scene.traverse(function(e){
if(e instanceof THREE.MESH && e!=plane){
...
}
});
雾:
//颜色 near far
scene.fog = new THREE.Fog(0xffffff,0.015,100);
//颜色 雾的浓度
scene.fog = new THREE.FogExp2(0xffffff, 0.015);
材质覆盖:
scene.overrideMaterial = new THREE.MeshLambertMaterial({color:0xffffff});
添加到场景中的物体都会使用当前的材质。
几何对象
手动创建几何对象:
var vertices = [
new THREE.Vector3(1,3,1),
new THREE.Vector3(1,3,-1),
new THREE.Vector3(1,-1,1),
new THREE.Vector3(1,-1,-1)
...
];
var faces = [
new THREE.Face3(0,2,1),
new THREE.Face3(2,3,1),
new THREE.Face3(4,6,5),
new THREE.Face3(6,7,5)
...
];
var geom = new THREE.Geometry();
geom.vertices = vertices;
geom.faces = faces;
geom.computeCentroids;
geom.mergeVertices();
出于性能的考虑,Three.js库假设一个网格的几何体在其声明周期内不会改变。但是,如果我们希望实时修改场景中渲染的物体,我们需要在renderer循环中额外设置:
mesh.geometry.vertices = vertices;
mesh.geometry.verticesNeedUpdate = true;//告知Three.js顶点需要更新
mesh.geometry.computeFaceNormals();//重新计算侧面的法线
使用多重材质:
var materials = [
new THREE.MeshLMaterial({opacity:0.6,color:0x44ff44,transparent:true}),
new THREE.MeshBasicMaterial({color:0x000000,wireframe:true})
];
var mesh = new THREE.SceneUtils.createMultiMaterialObject(geom,materials);
这行代码,不是场景一个mesh对象,而是创建了包含两个mesh对象(一个使用了MeshLambertMaterial材质,一个使用了MeshBasicMaterial材质)的组。这个组的使用方法,和mesh的使用方法类似。
mesh.children.forEach(function(e){
e.castShaow = true;
});
clone函数:
this.clone = function(){
var cloned = mesh.children[0].geometry.clone();
var materials = [
new THREE.MeshLMaterial({opacity:0.6,color:0x44ff44,transparent:true}),
new THREE.MeshBasicMaterial({color:0x000000,wireframe:true})
];
var mesh2 = THREE.SceneUtils.createMultiMaterialObject(cloned,materials);
mesh2.children.forEach(function(e){e.castShaow = true;});
mesh.translateX(5);
mesh.translateZ(5);
mesh2.name = "clone";
//移除之前的name叫 clone 的 物体。
scene.remove(scene.getChildByName('clone'));
scene.add(mesh2);
}
Mesh对象属性和函数:
一个Mesh对象的位置和是相对于其父对象来讲的。
定位:
cube.position.x =10;
cube.position.y =10;
cube.position.z =10;
cube.position.set(10,10,10);
cube.position = new THREE.Vector3(10,10,10);
旋转:
cube.rotation.x = 0.5*Math.PI;
cube.rotation.set(0.5*Math.PI,0,0);
cube.rotation = new THREE.Vector3(0.5*Math.PI,0,0);
平移:
cube.translateX(10);//相对当前位置沿x轴平移10个单位长度
相机:
PerspectiveCamera(fov,aspect,near,far);
OrthographicCamera(left,right,top,bottom,near,far);
camera.lookAt(new THREE.Vector3(x,y,z));
camera.lookAt(scene.position);