Search code examples
three.jsmodel3dloadcube

Three.js : How to add a 3D JSON model to one face of the cube's mesh


I am working on a small prototype in Three.js. I need to add a 3D JSON model to one of the faces of the cuboid. I can load the 3D model into the scene, but I couldn't able to add that model to the specific face of the cube.

Three.js script

 boxGeometry = new THREE.BoxGeometry(25, 25, 90, 7, 7, 7);
    var material = [
      new THREE.MeshBasicMaterial({ color: "#000000", wireframe:true}),
      new THREE.MeshBasicMaterial({ color: "#000000", wireframe:true}),
      new THREE.MeshBasicMaterial({ color: "#000000", wireframe:true}),
      new THREE.MeshBasicMaterial({ color: "#666699", wireframe:false}),
      // load 3D truck model to the mesh here, instead of the image
      new THREE.MeshBasicMaterial( { map: new THREE.TextureLoader().load( 'https://raw.githubusercontent.com/SatheeshKS10/MockRest/master/truck-front.png'), wireframe:false } ),
      new THREE.MeshBasicMaterial({ color: "#000000", wireframe:true})
  ];

The full code can be found here


Solution

  • Hope this helps some one !!

    As @Marquizzo mentioned we need to position / rotate the 3D object as required to place them on the exact position in the scene. Three.js offers many methods to parse different formats of 3D objects like - OBJLoader, GLTFLoader, etc.

    Below is a simple example using OBJ loader.

    var mtlLoader = new THREE.MTLLoader();
    mtlLoader.setTexturePath('/resources/');
    mtlLoader.setPath('/resources/');
    mtlLoader.load('3DModel.mtl', function(materials) { // this is optional to load material files !!
                                                        //  we can skip this if we have only obj files for our 3D model
    var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials(materials);
        objLoader.setPath('/resources/');
            objLoader.load('3DModel.obj', function(object3) {
                object3.rotation.set(3.15, 1.55, 0);
                object3.position.y = -25;
                object3.position.z = 10; 
                object3.position.x = 0; 
                scene.add(object3);     // Object is added to the scene.
            });
    
        });
    

    In the above code snippet, first we will load the MTL file and then we will load the 3D model's OBJ file.

    Next we will rotate & position the object to set it to the corresponding position.