Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js objloader + texture

I have been using Three.js for a few weeks now, I managed to apply a texture to a cube created directly via the code, but once I tried to load an OBJ file with OBJLoaderI noticed that I couldn't use the same method to load simple png or jpg textures with TextureLoader.

Now I'm not entirely sure what is going wrong, if either this is not the right way to do it, if I just can't load a simple image fine or if I'm not applying it right.

I've seen that applying a texture seems quite easy to do with an MTL file, but unfortunately I'm not sure how to make one.

My current code looks like something like this:

        var loader = new THREE.OBJLoader( manager );
        loader.load( 'models/tshirt.obj', function ( object ) {

            object.position.x = 0;
            object.position.y = -200;
            object.scale.x = 10;
            object.scale.y = 10;
            object.scale.z = 10;
            obj = object;
            texture = THREE.TextureLoader('img/crate.png'),
            material = new THREE.MeshLambertMaterial( { map: texture } );
            mesh = new THREE.Mesh( object, material );
            scene.add( mesh );

        } );

But it just doesn't seem to work. The model doesn't load and gives me random errors from Three.js. If instead of the code above I change scene.add( obj); the model actually loads.

What should I be doing here? Should I just go ahead and try to make an MTL file?

My full working code can bee seen at http://creativiii.com/3Dproject/old-index.html

EDIT: The error I get when adding mesh instead of obj is

three.min.js:436 Uncaught TypeError: Cannot read property 'center' of undefined
like image 503
Eight Avatar asked Oct 04 '16 10:10

Eight


1 Answers

Try this code:

var OBJFile = 'my/mesh.obj';
var MTLFile = 'my/mesh.mtl';
var JPGFile = 'my/texture.jpg';

new THREE.MTLLoader()
.load(MTLFile, function (materials) {
    materials.preload();
    new THREE.OBJLoader()
        .setMaterials(materials)
        .load(OBJFile, function (object) {
            object.position.y = - 95;
            var texture = new THREE.TextureLoader().load(JPGFile);

            object.traverse(function (child) {   // aka setTexture
                if (child instanceof THREE.Mesh) {
                    child.material.map = texture;
                }
            });
            scene.add(object);
        });
});

The texture loading changes was taken from: How to apply texture on an object loaded by OBJLoader? .

like image 125
Jack Pts Avatar answered Oct 31 '22 15:10

Jack Pts