javascript 如何让一个物体跟随鼠标在平面/地板上轻松/延迟在三个.js?

bq3bfh9z  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(95)

这已经是完美的工作:

const [dist, cycle] = useReducer((x) => (x % 4) + 1, 20);
useFrame(({ raycaster }) => {
    if (ref?.current) {
        raycaster?.ray?.at(dist, ref?.current?.position);
    }
});

实时演示:https://codesandbox.io/s/r3f-mouse-to-world-elh73?file=/src/index.js:311-315
我怎样才能添加一个小的延迟到动画,使对象不是立即在鼠标的位置?我怎样才能添加一个偏移,使它不是在鼠标的中心?

gg58donl

gg58donl1#

像往常一样,是我干的。

useFrame(({ raycaster }) => {
    const mouse = new Vector3(0, 0, 0);
    if (ref?.current) {
        //inject the raycast intersect point into mouse vec3
        raycaster?.ray?.at(dist, mouse);
        //get the object temp position
        const myPos = new Vector3(
            ref?.current?.position.x,
            ref?.current?.position.y,
            ref?.current?.position.z
        );
        //calculate the distance between mouse and object
        mouse.sub(myPos);
        //do the ease thing here, the higher the more ease
        mouse.divideScalar(10);
        //sumup:
        myPos.add(mouse);
        ref?.current?.position.set(myPos.x, myPos.y, myPos.z);
    }
});

相关问题