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

白昼怎懂夜的黑 提交于 2019-12-19 09:22:22

问题


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]);
            }   

        }

回答1:


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);
        }
});



回答2:


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.



来源:https://stackoverflow.com/questions/15669721/three-js-load-json-model-once-and-add-it-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!