threejs 自定义按钮实现glb模型动画切换

566 阅读1分钟

ui如图所示:

image.png glb动画模型有很多动画的话,可以通过重新渲染一次模型点击实现动画切换,但是重新渲染表示新增一个新的模型(这些所有模型在scene.children能看到所有在屏幕上重叠的模型),得将上一个渲染的模型删除掉,然后新增,我的代码如下这些(初始化也是这些代码,不过添加了一些判断用来删除重复的模型): `

function initModel(behavior: string) {
    // 加载 glb 格式模型
    const glbLoader = new GLTFLoader()

    glbLoader.load('/Models/RobotExpressive.glb', (gltf) => {
        const model = gltf.scene
        console.log(gltf)
        const animations = gltf.animations
        mixer = new THREE.AnimationMixer(model)

        let walkingAnimation = mixer.clipAction(animations.find(item => item.name === "Idle"))
        animationAction = mixer.clipAction(animations.find(item => item.name === behavior))

        if (preUuid) {
            if (model.uuid !== preUuid) {
                animationAction
                    .reset()
                    .setEffectiveTimeScale(1)
                    .setEffectiveWeight(1)
                    .fadeIn(0.2)
                    .play() // 被点击动画的执行

                if (behavior !== 'Walking') {
                    animationAction.loop = THREE.LoopOnce // 被点击动画只执行一次

                    if (behavior !== 'Death') {
                        setTimeout(() => {
                            walkingAnimation.play() // 被点击动画执行完成后继续执行 站立 动画
                        }, animationAction.time)
                    }
                }
                // 删除上一个模型进行中的动画
                scene.children.splice(scene.children.findIndex((item: any) => item.uuid === model.uuid), 1) 
            }
        } else {
            animationAction.play()
            preUuid = model.uuid
        }

        model.scale.set(40, 40, 40)

        // 模型的每个部位都可以投影
        model.traverse(function (child: any) {
            if (child && child.isMesh) {
                child.castShadow = true;
                child.receiveShadow = true;
            }
        });

`