Three.js-访问场景中的子对象 [英] Three.js - accessing a child object in a scene
问题描述
我正在尝试访问场景中的子对象sole
.我可以使用obj
在加载器函数内部访问var sole
,但是我需要从加载器函数外部访问它.
I'm trying to access the child object sole
in a scene. I am able to access the var sole
inside the loader function using obj
, but I need to access it from outside the loader function.
我可以从加载器内部访问它,如下所示:
I can access it from inside the loader, like this:
var loader = new THREE.ObjectLoader();
loader.load("models/shoe4.json", function (obj) {
scene.add (obj);
scene.rotation.y = Math.PI/1;
scene.position.y = -5;
scene.position.z = -24;
var sole = obj.getObjectByName( "sole", true );
sole.position.y = -5;
});
但是我需要做这样的事情:
But I need to do something like this:
var loader = new THREE.ObjectLoader();
loader.load("models/shoe4.json", function (obj) {
scene.add (obj);
scene.rotation.y = Math.PI/1;
scene.position.y = -5;
scene.position.z = -24;
});
var sole = obj.getObjectByName( "sole", true );
sole.position.y = -5;
基本上,我需要把它当作自己的函数供以后使用.
Basically I need to put it it's own function for later use.
我也尝试过
var sole = scene.getObjectByName( "sole", true );
sole.position.y = -5;
哪个给了我错误:
未捕获的TypeError:无法读取未定义的属性'
getObjectByName
'
如何从任何地方访问对象sole
?仅仅声明var obj,
不起作用.
How do I access the object sole
from anywhere? Simply declaring var obj,
is not working.
推荐答案
首先,您要在lambda函数的作用域之外声明sole
,如下所示:
First you declare sole
outside the scope of the lambda function, like this:
var sole = null;
var loader = new THREE.ObjectLoader();
loader.load("models/shoe4.json", function (obj) {
scene.add (obj);
scene.rotation.y = Math.PI/1;
scene.position.y = -5;
scene.position.z = -24;
sole = obj.getObjectByName( "sole", true );
sole.position.y = -5;
});
// this will FAIL because sole is undefined when this line of code executes
sole.position.x = 5;
第二,程序必须在实际执行lambda函数之后 后才能访问sole
.如果您不熟悉异步(或事件驱动)编程模型,那么应该对它进行一些阅读:
Second, the program must not access sole
until after the lambda function is actually executed. If you're not familiar with the asynchronous (or event-driven) programming model, then you should do a little reading about it:
http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027
https://msdn.microsoft.com/zh-我们/library/windows/apps/Hh700330.aspx
这篇关于Three.js-访问场景中的子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!