gpt4 book ai didi

javascript - 遍历 THREE.JS 中的 getObjectByName

转载 作者:太空宇宙 更新时间:2023-11-04 15:59:36 28 4
gpt4 key购买 nike

如何在遍历函数的父/子案例中使用 *.name 属性?oLoader.load() 是异步的。当我执行 object.traverse() 时,对象尚未加载。我该如何解决它?

这有效:

var geometry = new THREE.SphereGeometry(0.5, 32, 32);
var material = new THREE.MeshBasicMaterial({color: 0xffff00});
var sphere = new THREE.Mesh(geometry, material);
sphere.name = 'gomb';
scene.add(sphere);

var obj = scene.getObjectByName('gomb');
function remove(obj) {
scene.remove(obj);
}
remove(obj);

但这不起作用:

var oLoader = new THREE.OBJLoader();
oLoader.load('model/0004_02_00_FF_00_xxxxxx_0_00.obj', function (object, materials) {
var material_this = new THREE.MeshPhongMaterial({color: 0x00FF00});
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = material_this;
child.castShadow = true;
child.receiveShadow = true;
}
});

object.position.x = 0;
object.position.y = 0;
object.position.z = 0;
object.name = '0004_02_00_FF_00_xxxxxx_0_00';
scene.add(object);
});

var obj = scene.getObjectByName('0004_02_00_FF_00_xxxxxx_0_00', true);
function remove(obj) {
scene.remove(obj);
}
remove(obj);

最佳答案

一个技巧是在开始加载对象时立即将命名的父级添加到场景中,并在加载结束时检查父级是否仍然存在。

function loadObj(name, url, scene) {
var parent = new THREE.Object3D();
parent.name = name;
scene.add(parent);

var objLoader = new THREE.OBJLoader();
objLoader.load(url, function (object) {
var parent = scene.getObjectByName(name);
if (parent) {
parent.add(object);
}
});
}

如果对象正在加载,您就知道可以将其删除。

loadObj('my_object', 'model/0004_02_00_FF_00_xxxxxx_0_00.obj', scene);
var obj = scene.getObjectByName('my_object');
scene.remove(obj);

请注意,这需要在加载对象时知道对象的名称。

关于javascript - 遍历 THREE.JS 中的 getObjectByName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42385739/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com