如何在THREE.JS上创build自定义网格?
我问了这个,得到了答案:
var geom = new THREE.Geometry(); var v1 = new THREE.Vector3(0,0,0); var v2 = new THREE.Vector3(0,500,0); var v3 = new THREE.Vector3(0,500,500); geom.vertices.push(new THREE.Vertex(v1)); geom.vertices.push(new THREE.Vertex(v2)); geom.vertices.push(new THREE.Vertex(v3)); var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() ); scene.addObject(object);
我希望这个工作,但没有。
您已添加顶点,但忘记将这些顶点放入一个面并将其添加到几何:
geom.faces.push( new THREE.Face3( 0, 1, 2 ) );
所以你的片段变成:
var geom = new THREE.Geometry(); var v1 = new THREE.Vector3(0,0,0); var v2 = new THREE.Vector3(0,500,0); var v3 = new THREE.Vector3(0,500,500); geom.vertices.push(v1); geom.vertices.push(v2); geom.vertices.push(v3); geom.faces.push( new THREE.Face3( 0, 1, 2 ) ); var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() ); scene.addObject(object);
这个想法是通过使用列表/数组中的顶点的索引,Face3实例引用3个顶点(之前添加到几何的x,y,z坐标)。 目前你只有3个顶点,你想连接它们,所以你的脸在顶点数组中引用索引0,1和2。
由于您使用的是网格法线材质,因此您可能需要计算几何体的法线。 此外,请确保您的物体是可见的(不是太大或靠近相机被裁剪,朝着正确的方向 – 对着相机,等等)。因为你在YZ平面上画,看你的三angular形,这样的事情应该工作:
var geom = new THREE.Geometry(); var v1 = new THREE.Vector3(0,0,0); var v2 = new THREE.Vector3(0,500,0); var v3 = new THREE.Vector3(0,500,500); geom.vertices.push(v1); geom.vertices.push(v2); geom.vertices.push(v3); geom.faces.push( new THREE.Face3( 0, 1, 2 ) ); geom.computeFaceNormals(); var object = new THREE.Mesh( geom, new THREE.MeshNormalMaterial() ); object.position.z = -100;//move a bit back - size of 500 is a bit big object.rotation.y = -Math.PI * .5;//triangle is pointing in depth, rotate it -90 degrees on Y scene.add(object);
你可以自动化你的三angular测量
对于大的多边形,手动添加面可能是一项相当的工作。 您可以使用THREE.ShapeUtils
的triangulateShape
方法自动执行向网格添加面的过程,如下所示:
var vertices = [your vertices array]; var holes = []; var triangles, mesh; var geometry = new THREE.Geometry(); var material = new THREE.MeshBasicMaterial(); geometry.vertices = vertices; triangles = THREE.ShapeUtils.triangulateShape( vertices, holes ); for( var i = 0; i < triangles.length; i++ ){ geometry.faces.push( new THREE.Face3( triangles[i][0], triangles[i][1], triangles[i][2] )); } mesh = new THREE.Mesh( geometry, material );
vertices
是vertices
的数组,顶点可以在多边形中定义孔。
注意:小心,如果你的多边形是自相交会引发错误。 确保你的顶点数组代表一个有效的(不相交的)多边形。
THREE.Vertex已经在Three.js的最新版本中被弃用,所以不再需要这个部分:
geom.vertices.push(v1); geom.vertices.push(v2); geom.vertices.push(v3);