Threejs: Store jsonModel into a class variable

2019-08-23 04:05发布

问题:

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;
}

i have been trying to store it in this.soldier class variable, but never managed to succed. The object loading works fine.

回答1:

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.

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 );
});