javascripthtml3dthree.jsobjloader

THREE.js won't to load my .mtl and .obj file


I'm trying to create a 3d model viewer by using three.js but it won't load any .mtl and .obj files. I followed this tutorial https://manu.ninja/webgl-3d-model-viewer-using-three-js/ but it only loads the female model.

This is my script:

            var mtlLoader = new THREE.MTLLoader();
            mtlLoader.setBaseUrl('models/rayman2');
            mtlLoader.setPath('models/rayman2');
            mtlLoader.load('rayman_2_mdl.mtl', function (materials) {

                materials.preload();

                materials.materials.default.map.magFilter = THREE.NearestFilter;
                materials.materials.default.map.minFilter = THREE.LinearFilter;

                var objLoader = new THREE.OBJLoader();
                objLoader.setMaterials(materials);
                objLoader.setPath('models/rayman2');
                objLoader.load('rayman_2_mdl.obj', function (object) {

                    object.position.x = 0;
                    object.position.y = 0;
                    object.position.z = 0;
                    scene.add(object);

                }, null, null);

            });

Solution

  • You can convert the file to glTF here, then load it as follows:

    var loader = new THREE.GLTFLoader();
    loader.load('rayman.glb', function (gltf) {
      var content = gltf.scene;
      content.traverse((node) => {
        if (!node.isMesh) return;
        node.material.side = THREE.DoubleSide;
        node.material.alphaTest = 0.25;
        node.material.needsUpdate = true;
      });
      scene.add(content);
    }, undefined, function (e) {
      console.error(e);
    });
    

    The conversion to glTF just simplifies things. The other changes fix issues in the model: THREE.DoubleSide ensures that both sides of the character's hair are visible, and alphaTest ensures that the transparency in the texture appears correctly.

    enter image description here

    See docs for THREE.Material and THREE.GLTFLoader.

    three.js r92.