threejs从三角形创建网格

时间:2018-04-02 10:04:27

标签: three.js

我尝试使用以下代码创建网格。原因是我想这样的网格是让面部着色,然后在我解析x,y坐标时改变颜色。但是我得到一个" 绘制数组尝试从绑定数组中访问"错误。

for (var i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {

    vertices.push(-halfSize, 0, k, halfSize, 0, k);
    vertices.push(k, 0, -halfSize, k, 0, halfSize);
    var colorg = new THREE.Color("rgb(255, 0, 0)");
    colorg.toArray( colors, j ); j += 3;
        colorg.toArray( colors, j ); j += 3;
        colorg.toArray( colors, j ); j += 3;
        colorg.toArray( colors, j ); j += 3;

  }
  var vertices32 = new Float32Array(vertices);
  var colors32 = new Float32Array(colors);


  geometry.addAttribute('position', new THREE.BufferAttribute(vertices32, 3 ));
  geometry.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
  geometry.addAttribute('color', new THREE.BufferAttribute(colors32, 3));
  //fgeometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));

  // optional
  geometry.computeBoundingBox();
  geometry.computeBoundingSphere();

  // set the normals
  geometry.computeVertexNormals(); // computed vertex normals are orthogonal to the face for non-indexed BufferGeometry

  // material
  var material = new THREE.MeshPhongMaterial({
    color: 0xffffff,
    shading: THREE.FlatShading,
    vertexColors: THREE.VertexColors,
    side: THREE.DoubleSide
  });

  // mesh
  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

1 个答案:

答案 0 :(得分:0)

你试过BufferGeometry.toNonIndexed吗?通过这种方式,您可以创建法线PlaneBufferGeometry并将其转换为非索引几何体。每个面都有独特的顶点。

let geometry = new THREE.PlaneBufferGeometry();
geometry = geometry.toNonIndexed();

之后,您只需将颜色属性添加到几何体。完整的例子:

https://jsfiddle.net/f2Lommf5/4230/