1. 程式人生 > 其它 >微信小遊戲中從本地載入gltf模型

微信小遊戲中從本地載入gltf模型

技術標籤:Javascript微信小遊戲遊戲webjavascript小程式

參考https://threejs.org/examples/#webgl_animation_skinning_morph

在three.js的\examples\js\loaders下,有一個GLTFLoader.js檔案用來載入gltf模型。但是在微信小遊戲環境下,會遇到一些特殊的問題。

(1)把RobotExpressive.glb模型檔案放在程式碼目錄中時,上傳會提示“檔案型別不在白名單中,不會被上傳”,這個問題的解釋在:https://developers.weixin.qq.com/minigame/dev/guide/framework/code-package.html

因此,避開的方法是直接再加一個在白名單中的副檔名,如:RobotExpressive.glb.stl

(2)不能用GLTFLoader的load方法,因為他只支援http從遠端下載,要用parse方法:

let file='js/libs/three/RobotExpressive.glb.stl';
import { GLTFLoader } from './js/libs/three/GLTFLoader.js';
loadModel(file);
function loadModel(file){
        wx.showModal({
          content: file,
        })
        
        const fs = wx.getFileSystemManager();
        let content=fs.readFileSync(file);//,'binary');
        // console.log(content);
        //load方法無法載入wxfile://檔案,只能載入http://檔案
        let loader = new GLTFLoader();
        //loader.load(file, function (gltf) {
        loader.parse(content, file,function (gltf) {
            wx.showModal({
              content: 'gltf loaded.',
            });
            console.log('loaded glb');
            console.log(gltf.animations);
            console.log(gltf);
            let model = gltf.scene;
            model.scale.set(20,20,20);
            g_scene.add(model);
            const states = [ 'Idle', 'Walking', 'Running', 'Dance', 'Death', 'Sitting', 'Standing' ];
			const emotes = [ 'Jump', 'Yes', 'No', 'Wave', 'Punch', 'ThumbsUp' ];
            g_mixer = new THREE.AnimationMixer( model );
            const clip = gltf.animations[ 10 ];
            const action = g_mixer.clipAction( clip );
            if ( emotes.indexOf( clip.name ) >= 0 || states.indexOf( clip.name ) >= 4 )   {
                action.clampWhenFinished = true;
                action.loop = THREE.LoopOnce;

            }
            action.reset()
                .setEffectiveTimeScale( 1 )
                .setEffectiveWeight( 1 )
                .fadeIn( 0.5 )
                .play();
        },function(e){
            wx.showModal({
              content: 'gltf load fail'+JSON.stringify(e),
            });
        });
}