Three.js - 棋盘平面

时间:2014-03-27 13:59:57

标签: javascript three.js geometry plane

我正在尝试使用Three.js创建一个用于网页3D示例的棋盘格。但是,我目前的代码分配了三种颜色,我只需要两种颜色(黑/白)。如何重构数学以生成正确的棋盘?

// Geometry
var cbgeometry = new THREE.PlaneGeometry( 500, 500, 8, 8 );

// Materials
var cbmaterials = []; 

cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0xffffff, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x000000, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x0000ff, side: THREE.DoubleSide }) );

// Assign a material to each face (each face is 2 triangles)
var l = cbgeometry.faces.length / 2;

for( var i = 0; i < l; i ++ ) {
    var j = 2 * i;
    cbgeometry.faces[ j ].materialIndex = i % 3;
    cbgeometry.faces[ j + 1 ].materialIndex = i % 3;
}

// Mesh
cb = new THREE.Mesh( cbgeometry, new THREE.MeshFaceMaterial( cbmaterials ) );
scene.add( cb );

2 个答案:

答案 0 :(得分:3)

编辑:

如果我们的开发环境不同,我会建议这个代码修复:

EDIT-2:

索引选择部分中的&#39; j应该是,我现在就改变了。

试试这个:

// Geometry
var cbgeometry = new THREE.PlaneGeometry( 500, 500, 8, 8 );

// Materials
var cbmaterials = []; 

cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0xffffff, side: THREE.DoubleSide }) );
cbmaterials.push( new THREE.MeshBasicMaterial( { color: 0x000000, side: THREE.DoubleSide }) );

var l = cbgeometry.faces.length / 2; // <-- Right here. This should still be 8x8 (64)

console.log("This should be 64: " + l);// Just for debugging puporses, make sure this is 64

for( var i = 0; i < l; i ++ ) {
    j = i * 2; // <-- Added this back so we can do every other 'face'
    cbgeometry.faces[ j ].materialIndex = ((i + Math.floor(i/8)) % 2); // The code here is changed, replacing all 'i's with 'j's. KEEP THE 8
    cbgeometry.faces[ j + 1 ].materialIndex = ((i + Math.floor(i/8)) % 2); // Add this line in, the material index should stay the same, we're just doing the other half of the same face
}

// Mesh
cb = new THREE.Mesh( cbgeometry, new THREE.MeshFaceMaterial( cbmaterials ) );
scene.add( cb );

我评论了我在哪里进行换行。

我将Math.floor(i / 8)放在材质索引中以抵消每个其他图层。否则,它只是垂直线。

此外,第三种材料被移除,留下只有白色和黑色的工作。

感谢您提出这个问题,这很有趣!

答案 1 :(得分:1)

THREE.ShaderMaterial()怎么样?

顶点着色器可以是

varying vec2 vUv;
void main(){
vUv = uv;
gl_FragPosition = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

然后你的片段就像​​这样

varying vec2 vUv;
void main(){
vec2 tileUV = vec2(500.0, 500.0);//say you want to repeat it 500 times in both directions
vec2 repeatedUV = vUv * tileUV ;
repeatedUV -=floor(repeatedUV);

现在重复的UV有一堆瓦片,它们都是0-1范围内的vec2并重复

repeatedUV.x = floor(repeatedUV.x * 2.0);//should give black or white stripe in U direction
repeatedUV.y = floor(repeatedUV.y * 2.0);// same in the other way

然后这就像bool代数

float finalMask = repeatedUV.x + repeatedUV.y;//bottom left 0, bottom right 1, top left 1, top right 2
finalMask *= 1.0 - repeatedUV.x*repeatedUV.y; //all zero except top right
gl_FragColor = vec4(vec3(finalMask), 1.0);

}
我猜这是一种昂贵的做法,但可以节省你制作5000个三角形的费用。程序生成。