Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js - load JSON model once and add it multiple times

Is it possible to load a JSON model once and add it to the scene multiple times with different scales, positions, etc?

If I add the Object3D() to an array, give a position and scale to the object in the array, add it to the scene, and then repeat this process, the position and scale are overwritten for every object in the array.

I can't think of anything that works, so I'm hoping someone could give me a working example of what I'm trying to accomplish.

Here's (one of many) of my failed attempts. Should give you a basic idea of what I'm trying to do, if my explanation wasn't sufficient.

 function addModels(){

            var models = [];    

            var model = new THREE.Object3D();       
            var modelTex = THREE.ImageUtils.loadTexture( "textures/model.jpg" );
            var loader = new THREE.JSONLoader();
            loader.load( "models/model.js", function( geometry ) {
                mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { map: modelTex }) );
                model.add(mesh);
            } );

            for(var i = 0; i < 5; i++){ 
                model.scale.set(i,i,i);
                model.position.set(i,i,i);
                models[i] = model;

                scene.add(models[i]);
            }   

        }
like image 230
Broghain Avatar asked Sep 15 '25 07:09

Broghain


2 Answers

You need to clone a model first and then set position and scale.

 for(var i = 0; i < 5; i++){ 
        var newModel = model.clone();
            newModel.position.set(i,i,i);
            newModel.scale.set(i,i,i);

            scene.add(newModel); 
}  

Updated: Example how you can create json model without load : Fiddle example or just simple add loop inside load function.

like image 95
uhura Avatar answered Sep 17 '25 00:09

uhura


You can create new meshes from the same geometries and materials:

loader.load( "models/model.js", function( geometry ) {
        var mat = new THREE.MeshLambertMaterial( { map: modelTex });
        for (var i = 0; i < 5; i++) { 
            var mesh = new THREE.Mesh( geometry, mat );
            mesh.position.set(i, i, i);
            mesh.scale.set(i, i, i);
            scene.add(mesh);
        }
});
like image 41
Tapio Avatar answered Sep 17 '25 01:09

Tapio