WebGL/Three.js一个复杂对象(网格)上的不同材质

WebGL / Three.js Different materials on one complex object (grid)

本文关键字:网格 对象 一个 Three js WebGL 复杂      更新时间:2023-09-26

为了提高性能,我将网格渲染为一个THREE.Geometry()对象:

build : function(){    // simplified
  square = new THREE.Geometry();
  face = 0;
  for( r = 0; r < this["rows"]; r++)
   for( c = 0; c < this["cols"]; c++)
       // creates square
       square.vertices.push(new THREE.Vector3( x,  y, z));
       square.vertices.push(new THREE.Vector3( x + w, y, z));
       square.vertices.push(new THREE.Vector3( x + w, y - h, z));
       square.vertices.push(new THREE.Vector3( x, y - h, z));
       square.faces.push(new THREE.Face4(face + 0, face + 1, face + 2, face + 3));
       face+=4;
  // end of loops 

  // This adds material to the whole grid.
  // How to do it to each individual square?
  squareMaterial = new THREE.MeshBasicMaterial({
        color:"white",
        side:THREE.DoubleSide
  });
  grid = new THREE.Mesh(square, squareMaterial); 
  scene.add(grid);

比方说,我有一个函数,从网格中选择一组顶点(一个正方形),然后如何仅将颜色应用于这组顶点(正方形)?

在代码中,您使用一种材质创建一个对象网格。不能为对象的一部分设置新材质。在您的情况下,您可以编写自己的着色器,并将它们设置为属性(例如posx、posy和textere),或者按部分绘制网格(但这是个坏主意)

首先:将网格创建为具有多个线段(10x10)的平面几何体:

var planeGeo = new THREE.PlaneGeometry( 100, 100, 10, 10 );

第二:为你想改变材料(如颜色)的任何面设置materialIndex

像这样:

planeGeo.faces[5].materialIndex=1;

注意:默认materialIndex为0;

然后创建两个或多个材料并将其放入阵列中:

var materialsArray= [
        new THREE.MeshBasicMaterial({color:0xFF0000, side:THREE.DoubleSide}), // matIdx = 0
        new THREE.MeshBasicMaterial({color:0x00FF00, side:THREE.DoubleSide}) // matIdx = 1
    ];

然后创建一个多材料:

var multiMaterial = new THREE.MeshFaceMaterial( materialsArray );

然后创建网格并将其添加到场景中:

grid = new THREE.Mesh(planeGeo, squareMaterial); 
scene.add(grid);

希望有帮助,

M。

PS:

也许你必须绕X或Z轴旋转planeGeo 180度——我认为PlaneGeometry是在法线向下的情况下创建的——但不确定。

如果需要,你可以通过进行轮换

planeGeo.applyMatrix ( new THREE.Matrix4().makeRotationX(Math.PI) );