在.obj中加载后,如何保持Three.js对象的引用



官方文档提供了一个很好的示例,说明如何将.obj文件添加到场景中。

const loader = new OBJLoader();
// load a resource
loader.load(
// resource URL
'models/monster.obj',
// called when resource is loaded
function ( object ) {
scene.add( object );
},
// called when loading is in progresses
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);

但是,我不确定现在该如何操作加载的对象。URL用于加载对象,然后将加载的对象作为参数传递给加载函数,即传递给loader.load的第一个无名称函数。然而,保留对该对象的引用的"最佳"方式是什么?

这很简单。只需在调用加载函数之前创建一个引用。

const loader = new OBJLoader();
//Add a reference before loading model
var object;
//This is the same code, just without spaces/comments
loader.load('models/monster.obj', function ( object ) {
scene.add( object );
},
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
console.log( 'An error happened' );
});
//After loading, you can now manipulate the model
object.rotation.set(x, y, z);
object.position.set(x, y, z);

我可以管理的一种方法看起来不太好,但它很有效。

我可以简单地将它绑定到当前窗口或文档:

function ( object ) {
scene.add( object ); 
window.obj = object; // binding it to the window
}

但这对我来说似乎有点奇怪,因为这将把它与全球空间联系在一起。例如,如果我想让作用域更具包容性,该怎么办?

最新更新