5

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?

mustaccio
  • 18,234
  • 16
  • 48
  • 57
David Menard
  • 2,261
  • 3
  • 43
  • 67
  • http://stackoverflow.com/questions/8820591/how-to-use-multiple-materials-in-a-three-js-cube Is about the same question – Gero3 Sep 15 '12 at 15:39
  • Yes, I saw that one, but it's an older version of three.js and doesn't seem to work :( – David Menard Sep 15 '12 at 16:09

1 Answers1

11

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

user7290573
  • 1,320
  • 1
  • 8
  • 14
WestLangley
  • 102,557
  • 10
  • 276
  • 276