Threejs:将jsonModel存储到类变量中 [英] Threejs: Store jsonModel into a class variable
问题描述
我想使用类将已加载的json模型存储在Three.js中,我可以将其添加到场景中,但之后不能使用它. 我的代码如下所示:
i want to store a loaded json model in Three.js using classes, i can add it to the scene but i can't use it after. My code looks like this one:
class AScene extens THREE.Scene{
constructor(renderer){
super();
this.ground = null;
this.model = this.createModel() // it creates and return a model, which be the one encapsulating all models in this scene.
this.soldier = this.createSoldier(); // I want to store the loaded object here.
this.model.add(this.soldier); //doesn't work, always null or undefined;
this.add(this.model);
}
createModel(){
var model = new THREE.OBJECT3D();
this.ground = new Ground (300, 300, new THREE.MeshPhongMaterial ({map: textura}), 4);};
model.add(this.ground);
return model;
//this works fine.
}
createSoldier(){
var obj = null;
var loader2 = new THREE.JSONLoader();
loader2.load('models/untitled.json',function(geometry,materials){
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
obj = new THREE.Mesh( geometry, material );
});
}
return obj;
}
我一直试图将其存储在this.soldier类变量中,但从未成功.对象加载正常.
i have been trying to store it in this.soldier class variable, but never managed to succed. The object loading works fine.
推荐答案
由于在JSONLoader.load()
的onLoad()
回调中设置了obj
的实际值,因此createSoldier()
中的代码不起作用.此时,该方法已经返回了空值.
The code in createSoldier()
does not work since the actual value of obj
is set in the onLoad()
callback of JSONLoader.load()
. At this time, the method has already returned a null value.
您当前的类设计不支持JavaScript的异步字符.我认为您应该在继续工作之前使自己对回调和作用域更加熟悉.同时,您可以使用这种方法.
Your current class design does not honor the asynchronous character of JavaScript. I think you should make yourself more familiar with Callbacks and Scopes before you continue your work. In the meantime, you can use this approach.
loader2.load('models/untitled.json',(geometry,materials) => {
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
this.soldier = new THREE.Mesh( geometry, material );
});
这篇关于Threejs:将jsonModel存储到类变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!