在运行时加载 GLTF/GLB

在 Wonderland Engine 中构建大型项目时,您可能希望仅在需要时加载资产。运行时加载资产可以减少编辑器中的混乱,并为大型复杂场景提供动态加载解决方案。

Wonderland Engine 提供了两种在运行时加载资产的选项:从 .glb/.gltf 文件加载或流式加载 .bin 文件

启用运行时 GLTF 加载 

运行时 GLTF 加载是一项可选功能,需要在 Wonderland Editor 中启用。 打开您的项目,导航到 视图 > 项目设置 > 运行时,并选择 enableRuntimeGltf 复选框。

添加用于运行时加载的文件 

为运行时加载准备文件的最简单方法是将它们添加到项目的 static 文件夹中,其内容将在打包项目时复制到项目的 deploy 文件夹中。

deploy 文件夹是 Wonderland Editor 的网页服务器根目录,因此任何引用此处资产的 URL 都应相对于该目录指定。

示例: static/my-folder/my-model.glb 将被复制到 deploy/my-folder/my-model.glb,可通过 /my-folder/my-model.glb 访问(如果项目稍后部署到网页服务器的根路径),或 my-folder/my-model.glb

从 JavaScript 加载 

使用 WonderlandEngine.loadGLTF() 下载并解析 glTF/GLB 为 PrefabGLTF。然后使用 Scene.instantiate() 将其实例化到当前场景中。这提供了结构化的封装并避免过时的 API。

示例 

一个在应用启动时加载 .glb 文件并缩放它的组件可能如下:

import {Component, Property} from '@wonderlandengine/api';

export class LoadGlbAndScale extends Component {
    static TypeName = 'load-glb-and-scale';

    static Properties = {
        glbFile: Property.string('exampleGLB.glb'),
        scale: Property.float(1.0),
    };

    async start() {
        try {
            const prefab = await this.engine.loadGLTF({file: this.glbFile});
            const {root} = this.engine.scene.instantiate(prefab);
            root.setScalingWorld([this.scale, this.scale, this.scale]);
        } catch (error) {
            console.error('Failed to load GLB file:', error);
        }
    }
}

加载动画 

如果您的 .glb 文件包含动画,您可以通过实例化的层次结构访问它们,并根据需要添加 AnimationComponent。对于复杂的设置,建议在编辑器中制作动画并将其打包到您的主要 .bin 中,或者使用可流式传输的 .bin 文件以便在需要时加载。