After creating an OBJ file using Blender with two materials assigned, I successfully imported the file.
Now, my question is: How can I assign different materials to the faces in Three.js? I believe the materials need to be included in an array, but I'm unsure if I did it correctly. I want to assign the materials to the faces.
This snippet shows the relevant part of my code:
....
loader.load( './beardedbox3.obj', addBananaInScene);
};
var addBananaInScene = function(object){
banana = object;
// Moving the banana in the scene
banana.rotation.x = Math.PI/2;
banana.position.x = 0;
banana.position.y = 0;
banana.position.z = 0;
banana.scale.x = 200;
banana.scale.y = 200;
banana.scale.z = 200;
var white = new THREE.MeshPhongMaterial( { color: 0xffffff,
specular: 0xffffff,
shininess: 30,
shading: THREE.FlatShading } );
var red = new THREE.MeshPhongMaterial( { color: 0xff0000,
specular: 0xFF9900,
shininess: 30,
shading: THREE.FlatShading } );
object.traverse( function ( child ) {
if(child instanceof THREE.Mesh){
child.materials = [white, red];
child.geometry.computeVertexNormals();
}
});
// Adding the 3D object to the scene
scene.add(banana);
The structure of the OBJ file is as follows:
.... Vertex coordinates
usemtl white
s 1
f 1//1 2//1 3//1
f 4//2 5//2 6//2
... more faces
f 130//23 34//23 141//23
usemtl red
f 41//51 42//51 43//51
f 45//52 46//52 47//52
f 42//53 11//53
... additional faces
This appears to be a situation where a loop can be utilized to assign materials to faces. However, I am uncertain about how to proceed. Is there a simpler way?
Regards, Christian
Edit:
Thank you for your response. Your explanation makes sense, but I am struggling to make it work. It seems like there is a gap in my basic knowledge.
The key part of my updated code is as follows:
var white = new THREE.MeshPhongMaterial({
color: 0xffffff,
specular: 0xffffff,
shininess: 30,
shading: THREE.FlatShading
});
var red = new THREE.MeshPhongMaterial({
color: 0xff0000,
specular: 0xFF9900,
shininess: 30,
shading: THREE.FlatShading
});
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.materials = [white, red];
child.geometry.computeVertexNormals();
child.geometry.elementsNeedUpdate = true;
for (var i = 0; i < child.geometry.faces.length; i++) {
if (i < child.geometry.faces.length / 2) {
child.geometry.faces[i].materialIndex = 0;
} else {
child.geometry.faces[i].materialIndex = 1;
}
}
}
});
However, I encountered the following error message:
TypeError: child.geometry.faces is undefined
addBananaInScene/<() box.js:78
THREE.Object3D.prototype.traverse() three.min.js:179
THREE.Object3D.prototype.traverse() three.min.js:179
addBananaInScene() box.js:69
THREE.OBJLoader.prototype.load/<() OBJLoader.js:25
THREE.XHRLoader.prototype.load/<() three.min.js:377
It seems like I made a mistake somewhere. Any help would be greatly appreciated.
Christian