使用 useGLTF 加载模型
import { useMemo } from "react";
import { useGLTF } from "@react-three/drei";
const ReactLogo = () => {
const reactLogo = useMemo(() => useGLTF("./reactLogo/scene.gltf"), []);
return (
<mesh>
<primitive object={reactLogo.scene} rotation={[0, -5, 0]} scale={0.65} />
</mesh>
);
};
export default ReactLogo;
这里我们使用 useMemo 在组件渲染时缓存 useGLTF("./reactLogo/scene.gltf") 的结果,因为useGLTF 可能会有一些计算成本,将结果缓存起来可以避免在每次组件重新渲染时重新计算。
打开模型
这里需要使用到这里动画名称,使用 useAnimations 来进行动画加载,actions 来控制动画。
动画加载
import { useEffect, useMemo } from "react";
import { useAnimations, useGLTF } from "@react-three/drei";
const actionNames = [
"SphereAction",
"TorusAction1",
"TorusAction2",
"TorusAction3",
];
const ReactLogo = () => {
const reactLogo = useMemo(() => useGLTF("./reactLogo/scene.gltf"), []);
const { actions } = useAnimations(reactLogo.animations, reactLogo.scene);
useEffect(() => {
actionNames.forEach((actionName) => {
const action = actions[actionName];
if (action) {
action.play();
}
});
}, [actionNames, actions]);
//....
};
export default ReactLogo;
星空背景
从 @react-three/drei 中导出 Stars 模型。
import { useMemo } from "react";
import { Stars } from "@react-three/drei";
const StarsAnimated = () => {
const starProps = useMemo(
() => ({
radius: 1,
depth: 80,
count: 5000,
factor: 5,
saturation: 0,
fade: true,
speed: 2,
}),
[]
);
return <Stars {...starProps} />;
};
export default StarsAnimated;
使用 useFrame 执行渲染循环
import { useMemo, useRef } from "react";
import { useFrame } from "@react-three/fiber";
import { Stars } from "@react-three/drei";
const StarsAnimated = () => {
const starsRef = useRef();
//...
useFrame(() => {
starsRef.current.rotation.y += 0.0001;
starsRef.current.rotation.x += 0.0001;
starsRef.current.rotation.z += 0.0001;
});
return <Stars ref={starsRef} {...starProps} />;
};
export default StarsAnimated;
欢迎大家给个star~~~