Assigning materials to an OBJLoader model in three.js

后端 未结 3 1855

I\'ve imported an OBJ model with the following code:

var loader = new THREE.OBJLoader();
loader.addEventListener(\'load\', function (geometry) {
    object = geo         


        
相关标签:
3条回答
  • 2021-02-01 18:59

    EDIT: This answer is now outdated. Instead, see the answer by @mightypile.


    Assuming you have properly defined material, try this:

    loader.addEventListener( 'load', function ( event ) {
    
        var object = event.content;
    
        object.traverse( function ( child ) {
    
            if ( child instanceof THREE.Mesh ) {
    
                child.material = material;
    
            }
    
        } );
    
        scene.add( object );
    
    });
    
    0 讨论(0)
  • 2021-02-01 19:25

    I used SketchUp to produce my model. When I export from SketchUp to OBJ file format the resulting zip includes a MTL file;

    This code will load both the MTL file and the OBJ file; when you scene.add(object) after the successful load, the textures are automatically rendered (no need to assign to child.material.map)

    const loader = new OBJLoader(manager);
    
    const materialsLoader = new MTLLoader(manager);
    
    materialsLoader.load('models/obj/sketchup_export/d2e8bc61-6dd1-4554-b874-13b5364d656e.mtl', function (materialsCreator) {
    
        // https://threejs.org/docs/#examples/en/loaders/OBJLoader.setMaterials
        loader.setMaterials(materialsCreator);
    
    
        loader.load('models/obj/sketchup_export/d2e8bc61-6dd1-4554-b874-13b5364d656e.obj', function (obj) {
    
            object = obj;
    
        }, onProgress, onError);
    
    }, onProgress, onError);
    
    0 讨论(0)
  • 2021-02-01 19:26

    Using @WestLangley's answer, I kept getting the error

    loader.addEventListener is not a function
    

    and my page would not load. According to Atul_Mourya at discourse.threejs.org, it is a better (or more up-to-date?) idea to implement the function inside of a callback while loading. I combined his advice with the documentation and @WestLangley's helpful function answering this same question to come up with:

    var ship_material = new THREE.MeshBasicMaterial( { color: 0x444444 } );
    var loader = new THREE.OBJLoader();
    loader.load( 'ship.obj',
        function( obj ){
            obj.traverse( function( child ) {
                if ( child instanceof THREE.Mesh ) {
                    child.material = ship_material;
                }
            } );
            scene.add( obj );
        },
        function( xhr ){
            console.log( (xhr.loaded / xhr.total * 100) + "% loaded")
        },
        function( err ){
            console.error( "Error loading 'ship.obj'")
        }
    );
    

    This example also implements callbacks for progress and error, and it worked for me.

    0 讨论(0)
提交回复
热议问题