初探three.js幾何體-Geometry
阿新 • • 發佈:2019-12-27
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.