Three.js没有't在React中播放动画



我在React应用程序中加载从Sketchfab下载的GLTF模型。模型加载非常好,但根本无法播放动画。我尝试了不同的方法。有什么想法吗?

function Model({ url }) {
const model = useRef()
const { scene, animations } = useLoader(GLTFLoader, url)
const [mixer] = useState(() => new THREE.AnimationMixer())
useEffect(() => void mixer.clipAction(animations[0], group.current).play(), [])

return(
<primitive
ref={model}
object={scene}
/>
)
}

解决方案

  1. 我不得不使用节点而不是场景,并选择"根节点">(console.log节点,并选择在我看来是主节点的节点,该模型包含十几个节点(
  2. 使用useFrame按帧更新混合器
  3. 将动画应用于模型(有点更新(

工作代码:


function Model({ url }) {
const group = useRef()
const { nodes, scene, materials, animations } = useLoader(GLTFLoader, url)
const actions = useRef()
const [mixer] = useState(() => new THREE.AnimationMixer())
useFrame((state, delta) => mixer.update(delta))
useEffect(() => {
actions.current = { idle: mixer.clipAction(animations[0], group.current) }
actions.current.idle.play()
return () => animations.forEach((clip) => mixer.uncacheClip(clip))
}, [])

return(
<group ref={group} dispose={null}>
<primitive
ref={group}
name="Object_0"
object={nodes["RootNode"]}
/>
</group>
)
}

现在它工作

您需要在组件内部的useFrame中调用mixer.update(delta(:

import { useFrame } from 'react-three-fiber'
function Model({url}) {
.
. 
.
useFrame((scene, delta) => {
mixer?.update(delta)
})
.
. 
.
  • 将glb文件放入公共文件管理器中
import { Suspense, useEffect, useRef } from "react";
import { useAnimations, useGLTF } from "@react-three/drei";
export const Character = (props: any) => {
const ref = useRef() as any;
const glf = useGLTF("assets/Soldier.glb");
const { actions } = useAnimations(glf.animations, ref);
useEffect(() => {
actions.Run?.play();
});
return (
<Suspense fallback={null}>
<primitive 
ref={ref} 
object={glf.scene}
/>
</Suspense>
);
};

最新更新