初探three.js几何体-Geometry

three.js几何体我们还没有说完,这一节我们说一说THREE.Geometry(),简单几何体都是继承了这个对象,使用它会相对麻烦一些,但是可操作性非常高,今天我们使用它制作一个自定义几何体-五角星,我们先开看一下效果。mode请移步至 郭志强的博客

Geometry对象有两个比较重要的属性
1. vertices对象,他保存几何体所有点信息,是一个三维点数组
2. faces对象,他保存所有面信息,是一个THREE.Face3数组
所以我们先创建组成五角星的点,然后添加到vertices对象中。

let points = [];
points.push(new THREE.Vector3(0, 0, gui.thickness))
points.push(new THREE.Vector3(0, 0, - gui.thickness))
for(let i=0; i<5; i++) {
    points.push(new THREE.Vector3(Math.sin(Math.PI * 2 / 5 * i) * gui.size_long, Math.cos(Math.PI * 2 / 5 * i) * gui.size_long, 0))
    points.push(new THREE.Vector3(Math.sin(Math.PI * 2 / 5 * i + Math.PI * 2 / 10) * gui.size_short, Math.cos(Math.PI * 2 / 5 * i + Math.PI * 2 / 10) * gui.size_short, 0))
}
geometry.vertices = points;

点加完了,我们开说一说面,在three.js中,一个面是由三个点组成(新版本要求必须为3个点),但是由于点的排列顺序有顺时针和逆时针两种,我们想要看到面,就需要让三个点沿逆时针排序,下面来创建点。

geometry.faces.push(new THREE.Face3(0, 3, 2));
geometry.faces.push(new THREE.Face3(0, 4, 3));
geometry.faces.push(new THREE.Face3(0, 5, 4));
geometry.faces.push(new THREE.Face3(0, 6, 5));
geometry.faces.push(new THREE.Face3(0, 7, 6));
geometry.faces.push(new THREE.Face3(0, 8, 7));
geometry.faces.push(new THREE.Face3(0, 9, 8));
geometry.faces.push(new THREE.Face3(0, 10, 9));
geometry.faces.push(new THREE.Face3(0, 11, 10));
geometry.faces.push(new THREE.Face3(0, 2, 11));
geometry.faces.push(new THREE.Face3(1, 2, 3));
geometry.faces.push(new THREE.Face3(1, 3, 4));
geometry.faces.push(new THREE.Face3(1, 4, 5));
geometry.faces.push(new THREE.Face3(1, 5, 6));
geometry.faces.push(new THREE.Face3(1, 6, 7));
geometry.faces.push(new THREE.Face3(1, 7, 8));
geometry.faces.push(new THREE.Face3(1, 8, 9));
geometry.faces.push(new THREE.Face3(1, 9, 10));
geometry.faces.push(new THREE.Face3(1, 10, 11));
geometry.faces.push(new THREE.Face3(1, 11, 2));
geometry.faces.forEach((d,i) => geometry.faces[i].materialIndex = i % 2)
geometry.computeFaceNormals();

一共有20个面,倒数第二行我们为faces中数组的每一项设置materialIndex值,稍后我们在说。最后一行是重新计算面的法向量。
最后我们为每一个面个性化材质。

let mate1 = new THREE.MeshBasicMaterial({color: 0xffaa00})
let mate2 = new THREE.MeshBasicMaterial({color: 0x00ff00})
var faceMaterial = new THREE.MeshFaceMaterial([mate1, mate2]);
mesh = new THREE.Mesh(geometry, faceMaterial);

这里说到了THREE.MeshFaceMaterial对象,它允许我们为不同的面设置材质,它会对应geometry.faces数组中每一项的materialIndex值,由于我们把奇数项的materialIndex设置成了0,偶数项设置成了1,所以五角星的面形成了交替颜色。

今天就先说这么多,下一节说一说二维操作网格。
转载请注明原文地址  https://www.cnblogs.com/vadim-web/p/12106006.html

posted @ 2019-12-27 10:32  郭先生的博客  阅读(339)  评论(0编辑  收藏