【babylonjs】babylonjs实践(十)--模型导入

5,611 阅读2分钟

背景

自己画的组装车不好看,那么就导入一个模型好了。

api

ImportMesh

Import​Mesh(meshNames: any, rootUrl: string, sceneFilename?: string | File, scene?: Nullable<Scene>, onSuccess?: Nullable<SceneLoaderSuccessCallback>, onProgress?: Nullable<(event: ISceneLoaderProgressEvent) => void>, onError?: Nullable<(scene: Scene, message: string, exception?: any) => void>, pluginExtension?: Nullable): Nullable<ISceneLoaderPlugin | ISceneLoaderPluginAsync>

注意: <script src="https://preview.babylonjs.com/loaders/babylonjs.loaders.min.js"></script> 引入插件以后,可以使用SceneLoader类加载模型,它提供了一些加载方法。

SceneLoader

SceneLoader.Append

从文件文件夹中加载所有的模型资源并添加到babylon场景中

配置项:文件夹路径,资源名称,场景对象,回调函数

BABYLON.SceneLoader.Load("/assets/", "batman.obj", engine, function (newScene) { // ... });

SceneLoader.ImportMesh

从文件中加载模型并将它们添加到场景中,这个和Append区别在于,回调返回的是模型对象而不是场景对象。我们可以在成功的回调里面对模型再进行进一步的处理。
配置项:将要添加到场景中的模型名称或为空(将所有模型或者骨骼加载),文件夹路径,资源名称,场景对象,回调函数

BABYLON.SceneLoader.ImportMesh(["myMesh1", "myMesh2"], "./", "duck.gltf", scene, function (meshes, particleSystems, skeletons) { // 对骨骼和模型进行进一步操作 // 对于glTF文件,粒子系统默认为空 });\

SceneLoader.LoadAssetContainer

从文件夹中添加所有的资源到babylon,但不会自动添加到场景中
配置项:文件夹路径,资源名称,场景对象,回调函数

BABYLON.SceneLoader.LoadAssetContainer("./", "duck.gltf", scene, function (container) {
    var meshes = container.meshes;
    var materials = container.materials;
    //...

    // Adds all elements to the scene
    container.addAllToScene();
});

回调函数会返回一个容器对象,里面包含所有模型加载的资源光源,模型,相机等等。如果需要将模型添加到场景,需要使用:

container.addAllToScene();

将添加的容器内容从场景中删除,则使用:

container.removeAllFromScene();

SceneLoader.AppendAsync

我们还可以通过使用Async函数来实现链式回调:

BABYLON.SceneLoader.AppendAsync("./", "duck.gltf", scene).then(function (scene) {
    // do something with the scene
});

正文

                BABYLON.SceneLoader.ImportMesh("", "http://10.101.16.11:5000/common/", "testee.stl", scene, function (meshes){
                    var car = meshes[0]
                    var mat2 = new BABYLON.StandardMaterial("texture3", scene);
                    mat2.diffuseColor = new BABYLON.Color3(1, 0, 1)
                    // mat2.diffuseTexture = new BABYLON.Texture("http://10.101.16.11:5010/static/file/test.png", scene);

                    car.material = mat2
                    car.rotation.x = Math.PI / 2
                    car.position.y = 0.5
                    console.log(meshes, '123')
                })

image.png

但是有个问题,纹理加载不上。

image.png

模型是自带纹理的,因为纹理贴到模型上有特定的uv映射关系。

不能随便找一张纹理就贴到模型上,一般加载模型的时候会自动加载模型自带的纹理

模型格式

目前支持的文件格式类型:

那么模型都是哪儿下载的呢?

UE中可以导出模型。

然后去收费网站上买。

暂时没有看到免费的模型网站。。。。