Three.js - 访问场景中的子对象

Three.js - accessing a child object in a scene

我正在尝试访问场景中的子对象 sole。我可以使用 obj 访问加载程序函数内部的 var sole,但我需要从加载程序函数外部访问它。

Here's the working codehere's the json model file.

我可以从加载程序内部访问它,如下所示:

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;

});

但我需要做这样的事情:

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;

基本上我需要把它放在它自己的功能以备后用。

我也试过了

var sole = scene.getObjectByName( "sole", true );
sole.position.y = -5;

这给了我错误:

Uncaught TypeError: Cannot read property 'getObjectByName' of undefined

如何从任何地方访问对象 sole?简单地声明 var obj, 是行不通的。

首先你在 lambda 函数的范围之外声明 sole,像这样:

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;

其次,程序不得访问sole,直到 lambda 函数实际执行之后。如果您不熟悉异步(或事件驱动)编程模型,那么您应该阅读一下它:

http://code.tutsplus.com/tutorials/event-based-programming-what-async-has-over-sync--net-30027

https://msdn.microsoft.com/en-us/library/windows/apps/Hh700330.aspx