Threejs: Store jsonModel into a class variable

风流意气都作罢 提交于 2019-12-11 18:27:29

问题


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


来源:https://stackoverflow.com/questions/50276831/threejs-store-jsonmodel-into-a-class-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!