Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge three.js meshes into one Mesh?

Is it possible in Three.js to merge two or more meshes, with different materials?

The solutions I've found, merges geometry only, or just puts the Meshes into one Object3D or Group.

like image 403
Iter Ator Avatar asked Mar 15 '23 03:03

Iter Ator


1 Answers

Yes: Kind-of (see the comments attached to the question and this answer post):

var blueMaterial = new THREE.MeshPhongMaterial( {color: 0x0000FF } );
var redMaterial = new THREE.MeshPhongMaterial({ color:0xFF0000 });
var meshFaceMaterial = new THREE.MeshFaceMaterial( [ blueMaterial, redMaterial ] );

var boxGeometry = new THREE.BoxGeometry( 10, 10, 10 );

for ( var face in boxGeometry.faces ) {
    boxGeometry.faces[ face ].materialIndex = 0;
}

var sphereGeometry = new THREE.SphereGeometry( 5, 16, 16 );
sphereGeometry.applyMatrix( new THREE.Matrix4().makeTranslation(0, 5, 0) );

var mergeGeometry = new THREE.Geometry();
mergeGeometry.merge( boxGeometry, boxGeometry.matrix );
mergeGeometry.merge( sphereGeometry, sphereGeometry.matrix, 1 );

var mesh = new THREE.Mesh( mergeGeometry, meshFaceMaterial );
scene.add( mesh );

I went with a cube and a sphere because a box for example wants to know a material id for each of its faces.

http://jsfiddle.net/v49ntxfo/

like image 166
Falk Thiele Avatar answered Mar 28 '23 12:03

Falk Thiele