Вопрос

I'm trying to populate an object-literal with Three.js Object3Ds and then populate the Object3Ds with meshes. However I'm getting some strange results from my code. I've distilled the problem to the barest lines of code that still replicate the problem. In the scenario below thing1 and thing2 receive no meshes and thing3 receives all three meshes:

var objSet = {
    thing1: new THREE.Object3D(),
    thing2: new THREE.Object3D(),
    thing3: new THREE.Object3D()
};

for (key in objSet) {
    objSet[key].add(aMesh);
    objSet[key].add(anotherMesh);
    objSet[key].add(yetAnotherMesh);
};

My eventual goal is to dynamically create an object-literal filled with Object3Ds an then reliably loop through and add meshes to each. Where is the problem here? Thanks for taking a look!

Это было полезно?

Решение

Following the guidance of the folks above in the comments, I discovered that the reason for the strange behavior in my code (the console.logs indicated that each Object3D in the object-literal was being filled with meshes during the run, but at the end all but the last Object3D were empty) was that meshes can be used only once and I needed to copy them into the Object3Ds, otherwise they were simply jumping from one to the next as I assigned them. Oi!

The fix was quick and easy - simply add .clone() to the end of the mesh variable in the .add() function:

var objSet = {
    thing1: new THREE.Object3D(),
    thing2: new THREE.Object3D(),
    thing3: new THREE.Object3D()
};

for (key in objSet) {
    objSet[key].add(aMesh.clone());
    objSet[key].add(anotherMesh.clone());
    objSet[key].add(yetAnotherMesh.clone());
};

Thanks all!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top