Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - multiple material plane

I'm trying to have multiple materials on a single plane to make a simple terrain editor. So I create a couple of materials, and try to assign a material index to each vertex in my plane:

var materials = [];
materials.push(new THREE.MeshFaceMaterial( { color: 0xff0000 }));
materials.push(new THREE.MeshFaceMaterial( { color: 0x00ff00 }));
materials.push(new THREE.MeshFaceMaterial( { color: 0x0000ff }));
// Plane
var planegeo = new THREE.PlaneGeometry( 500, 500, 10, 10 );
planegeo.materials = materials;
for(var i = 0; i <  planegeo.faces.length; i++)
{
    planegeo.faces[i].materialIndex = (i%3);
}

planegeo.dynamic = true;
this.plane = THREE.SceneUtils.createMultiMaterialObject(planegeo, materials);

But I always get either a whole bunch of errors in the shader, or only a single all-red plane if I use MeshBasicMaterial instead of FaceMaterial. What am I doing wrong?

like image 376
David Menard Avatar asked Sep 15 '12 15:09

David Menard


1 Answers

To get a checkerboard pattern with three colors do this:

// geometry
var geometry = new THREE.PlaneGeometry( 500, 500, 10, 10 );

// materials
var materials = [];
materials.push( new THREE.MeshBasicMaterial( { color: 0xff0000 }) );
materials.push( new THREE.MeshBasicMaterial( { color: 0x00ff00 }) );
materials.push( new THREE.MeshBasicMaterial( { color: 0x0000ff }) );

// assign a material to each face (each face is 2 triangles)
var l = geometry.faces.length / 2;
for( var i = 0; i < l; i ++ ) {
    var j = 2 * i;
    geometry.faces[ j ].materialIndex = i % 3;
    geometry.faces[ j + 1 ].materialIndex = i % 3;
}

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

EDIT: Updated for three.js r.60

like image 199
WestLangley Avatar answered Oct 12 '22 14:10

WestLangley