我正在使用three.js创建一个场景,我正在添加3个球体。然后我试图将从线框创建的所有球体切换到非线框材质。我没有使用scene.traverse(),因为我的场景中有更多的对象,我只想切换球体,但是使用这个代码,我只能切换一个球体。我怎样才能进入每个领域?有帮助吗?谢谢!
var numSpheres = 3;
function createSphere (x, y, z){
sphere = new THREE.Object3D();
material = new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true});
geometry = new THREE.SphereGeometry (2, 8, 8);
mesh = new THREE.Mesh(geometry, material);
sphere.add(mesh);
sphere.position.set(x, y, z);
scene.add(sphere);
}
createSpheres(numSpheres){
for(i = 1; i <= numSpheres; i++){
var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
createSphere(randomnumber1, 3, randomnumber2);
}
}
function onKeyDown(e){
case 65:
case 97:
sphere.traverse(function (node){
if(node instanceof THREE.mesh) {
node.material.wireframe = !node.material.wireframe;
}
});
答案 0 :(得分:0)
正如@ prisoner849建议的那样,将您想要操作的对象放在数组或映射中(如@ prisoner849建议的那样)。这样,您就可以避免测试dataGridView
,并且只操纵想要操作的对象。
instanceof THREE.Mesh
答案 1 :(得分:0)
如果您将来可以逐个到达您的球体,则大多数亲戚都是对象中的数组:
function createSphere (x, y, z){
var sphere= new THREE.Mesh(new THREE.SphereGeometry (2, 8, 8), new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true}));
scene.add(sphere);
sphere.position.set(x, y, z);
return sphere;
}
mySpheres = {};
mySpheres.models = [];
mySpheres.materials = [];
for(i = 1; i <= 3; i++){
var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
var obj = createSphere(randomnumber1, 3, randomnumber2); //
var id = obj.id; // or whartever (redone,barrack,donald,george)
mySpheres.models[id] = obj;
mySpheres.materials.push(obj.material);
}
//after that you can do
mySpheres.models['donald'].translateX(10);
//or
mySpheres.models['george'].material.opacity = 0.5;
//or
mySpheres.materials.forEach(function(m) {
m.opacity = 0.5;
});