Threejs:将jsonModel存储到类变量中

时间:2018-05-10 15:52:31

标签: javascript oop model three.js

我想使用类在Three.js中存储一个加载的json模型,我可以将它添加到场景中但我不能在之后使用它。 我的代码看起来像这样:

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类变量中,但从未设法成功。对象加载工作正常。

1 个答案:

答案 0 :(得分:1)

createSoldier()中的代码不起作用,因为在obj的{​​{1}}回调中设置onLoad()的实际值。此时,该方法已返回空值。

您当前的类设计不尊重JavaScript的异步字符。我认为在继续工作之前,你应该让自己更熟悉Callbacks和Scopes。与此同时,您可以使用这种方法。

JSONLoader.load()