问题描述
为了提高性能,我在这样的循环中将网格渲染到一个 THREE.Geometry() 对象:
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) ?
推荐答案
首先:将网格创建为具有多个线段 (10x10) 的平面几何体:
first: create the grid as a plane geometry with multiple segments (10x10):
var planeGeo = new THREE.PlaneGeometry( 100, 100, 10, 10 );
第二个:为你想要改变材质的任何面设置 materialIndex(例如颜色)
second: set materialIndex for whatever face you wish to change the material (eg color)
像这样:
planeGeo.faces[5].materialIndex=1;
注意:默认materialIndex为0;
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
];
然后创建一个多材质:
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);
希望能帮到你,
M.
附注:
也许您必须围绕 X 轴或 Z 轴将 planeGeo 旋转 180 度 - 我认为 PlaneGeometry 是在法线向下的情况下创建的 - 但不确定.
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) );
这篇关于WebGL/Three.js 一个复杂对象(网格)上的不同材料的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!