【问题标题】:Three,js get mesh outside the loader三、js在loader外获取mesh
【发布时间】:2021-11-22 18:28:23
【问题描述】:

我正在使用 Three.js 开发一个项目。 而且,我正在尝试从外部加载 GLTF 中的网格(gltf.scene),但是如果我在加载器之外使用 console.log,它表示它是未定义的。我花了几个小时来解决这个问题,但无法解决这个问题。我猜这是因为它是异步的,但我不太确定。 这是我第一次尝试使用 javascript 类格式,所以我有点困惑。通常,如果我在更高的范围内声明变量并将网格分配给它,它会起作用,但这次不起作用。

class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loader = new GLTFLoader();
this.loader.load("./c.glb",(gltf)=>{
this.character= gltf.scene;
});
console.log(this.character);


}

我也试过做异步功能,但没用。

class mainCharacter {
  constructor(game) {
...
...
...
this.character;
this.loadMain();
console.log(this.character);
})

async loadMain(){
    const loader = new GLTFLoader();
    this.character = await loader.loadAsync("./c.glb");
    this.character.scene.scale.set(13, 13, 13);
    this.scene.add(this.character.scene);
}

如果我在 loadMain() 和 console.log(this.character) 前面使用 await 似乎它可以工作,但我不能在构造函数中使用 await,因为它不是异步函数。 如果有人有任何想法,请帮助我:'(

谢谢!

【问题讨论】:

    标签: javascript asynchronous module three.js gltf


    【解决方案1】:

    根据 ThreeJS 文档 (https://threejs.org/docs/#api/en/loaders/Loader.loadAsync),方法 loadAsync 不返回加载的网格,而是返回一个 Promise 事件。

    .loadAsync ( url : String, onProgress : Function ) : Promise
    

    因此,您需要声明一个 onLoad 回调函数,如下所示:

    this.character = await loader.loadAsync("./c.glb").then(function(value) {
      console.log(value); // "Success"
    });
    

    【讨论】:

      【解决方案2】:

      在您的类中定义另一个静态方法(如下所示的load)并将this 作为参数传递

      class mainCharacter {
        constructor(game) {
          ...
          this.character;
          this.loader;
          mainCharacter.load(this);
          ...
        }
        static load(self) {
          self.loader = new GLTFLoader();
          self.loader.load(
            "./c.glb",
            (gltf) => self.character = gltf.scene
          );
        }
      }
      

      在箭头函数中,this 指向该函数的所有者,或定义该特定箭头函数的对象。 在您的情况下,箭头函数内的this 并不指向mainCharacter 对象,因为它实际上是在loader.load() 函数中定义并传递给的。 详情请见https://www.w3schools.com/js/js_arrow_function.asp

      【讨论】:

        猜你喜欢
        • 2012-08-02
        • 1970-01-01
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 2019-10-11
        • 1970-01-01
        相关资源
        最近更新 更多