如何在Three.js中让物体带延迟缓动跟随平面鼠标并添加偏移?
为R3F物体添加鼠标跟随延迟与偏移
原实现代码
const [dist, cycle] = useReducer((x) => (x % 4) + 1, 20); useFrame(({ raycaster }) => { if (ref?.current) { raycaster?.ray?.at(dist, ref?.current?.position); } });
问题
请问如何为该动画添加小延迟,使物体不会立刻到达鼠标位置?以及如何添加偏移,让物体不处于鼠标中心?
一、添加延迟(缓动跟随效果)
要实现延迟跟随,核心是让物体位置逐步趋近鼠标对应的目标位置,而非直接赋值。可以借助useRef存储目标位置,再用线性插值实现平滑过渡:
import { useRef } from 'react'; import * as THREE from 'three'; // 存储目标位置,定义缓动系数(越小延迟越高) const targetPos = useRef(new THREE.Vector3()); const smoothFactor = 0.05; const [dist, cycle] = useReducer((x) => (x % 4) + 1, 20); useFrame(({ raycaster }) => { if (ref?.current) { // 先计算鼠标对应的目标位置 raycaster?.ray?.at(dist, targetPos.current); // 让物体位置逐步趋近目标位置 ref.current.position.lerp(targetPos.current, smoothFactor); } });
lerp方法会让物体每次向目标位置移动smoothFactor比例的距离,调整这个系数就能控制延迟程度——系数越小,跟随越平缓,延迟感越强。
二、添加鼠标中心偏移
只需在计算目标位置时,给射线得到的坐标加上自定义偏移向量即可:
import * as THREE from 'three'; // 定义三维空间内的偏移量,可按需调整x/y/z轴数值 const offset = new THREE.Vector3(0.5, 0.5, 0); const [dist, cycle] = useReducer((x) => (x % 4) + 1, 20); useFrame(({ raycaster }) => { if (ref?.current) { const target = new THREE.Vector3(); raycaster?.ray?.at(dist, target); // 给目标位置添加偏移 target.add(offset); // 结合缓动的话就用lerp,不需要缓动直接用copy赋值 ref.current.position.lerp(target, smoothFactor); } });
如果需要动态偏移(比如随鼠标方向变化),可以把offset改成响应式变量,根据业务逻辑实时调整数值。
内容的提问来源于stack exchange,提问作者Suisse
相关产品推荐
相关产品推荐

