如何在THREE.JS上创建自定义网格?

时间:2012-02-12 21:19:34

标签: javascript three.js

我已经问了这个并得到了答案:

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);

我希望这可行,但它没有。

3 个答案:

答案 0 :(得分:68)

您已添加顶点,但忘记将这些顶点放入面中并将其添加到几何体中:

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平面上绘图,看到你的三角形,这样的东西应该有效:

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);

答案 1 :(得分:25)

您可以自动化三角测量

对于大多边形,手动添加面可能非常重要。您可以使用the triangulateShape method in THREE.ShapeUtils自动执行向网格添加面的过程,如下所示:

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是您的顶点数组且holes,您可以在多边形中定义孔。

注意:请注意,如果您的多边形是自相交的,则会引发错误。确保顶点数组表示有效(非相交)多边形。

答案 2 :(得分:10)

THREE.Vertex已在最新版本的Three.js中弃用,因此不再需要该部分:

geom.vertices.push(v1);
geom.vertices.push(v2);
geom.vertices.push(v3);