前言
本篇继续给大家分享一下,在three.js中如何播放模型自动的动画
首页在上一篇 three.js加载外部glb,fbx,gltf,obj 模型文件 的文章基础上
一.新加入三个函数方法
- 开始执行动画方法: onStartModelAnimaion
- 设置模型动画方法:onSetModelAnimaion
- 模型动画帧渲染方法:animationFrameFun
- 获取当前模型动画方法:getModelAnimaionList
// 开始执行动画
function onStartModelAnimaion(config) {
this.onSetModelAnimaion(config)
cancelAnimationFrame(this.animationFram)
this.animationFrameFun()
}
// 设置模型动画
function onSetModelAnimaion({ animations, animationName, loop, timeScale, weight }) {
this.animationMixer = new THREE.AnimationMixer(this.model)
const clip = THREE.AnimationClip.findByName(animations, animationName)
if (clip) {
this.animateClipAction = this.animationMixer.clipAction(clip)
this.animateClipAction.setEffectiveTimeScale(timeScale)
this.animateClipAction.setEffectiveWeight(weight)
// 动画播放的方式
this.animateClipAction.setLoop(this.loopMap[loop])
this.animateClipAction.play()
}
}
// 动画帧
function animationFrameFun() {
this.animationFram = requestAnimationFrame(() => this.animationFrameFun())
if (this.animationMixer) {
this.animationMixer.update(this.animationColock.getDelta())
}
}
// 获取当前模型动画
function getModelAnimaionList(result) {
this.modelAnimation =result.animations || []
}
二.在页面中去使用
<script setup>
import { reactive, computed } from "vue";
const store = useMeshEditStore();
const config = reactive({
animationName: null, //动画名称
loop: "LoopRepeat", // 循环方式 TODO:LoopOnce 执行一次 LoopRepeat 循环执行 LoopPingPong 来回执行
timeScale: 1, // 播放速度
weight: 1, // 动作幅度
});
// 选择动画
const onChangeAnimationType = ({ name }) => {
config.animationName = name;
store.modelApi.onStartModelAnimaion(config);
};
</script>