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

☆樱花仙子☆ 提交于 2019-12-24 01:25:30

问题


In order to increase performance i render grid to one THREE.Geometry() object in such loop:

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

Lets say, i have a function that selects the set of vertices (one square) from the grid (mesh) how then apply color to only this set of vertices (square) ?


回答1:


In your code you create a one object grid with one material. You cant set new material for part of object. In your case you can write your own shader and set them attributes pos.x, pos.y and textere for example or draw your grid by parts (but this is a bad idea)




回答2:


first: create the grid as a plane geometry with multiple segments (10x10):

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

second: set materialIndex for whatever face you wish to change the material (eg color)

like so:

planeGeo.faces[5].materialIndex=1;

note: default materialIndex is 0;

then create two or more materials and put them into array:

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

then create a multimaterial:

var multiMaterial = new THREE.MeshFaceMaterial( materialsArray );

then create the mesh and add it to the scene:

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

Hope it helps,

M.

PS:

maybe you'll have to rotate the planeGeo 180degs around X or Z axis - I think the PlaneGeometry is created with normals down - but not sure.

if needed, you'd do the rotation by:

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


来源:https://stackoverflow.com/questions/17489930/webgl-three-js-different-materials-on-one-complex-object-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!