Search code examples
reactjsthree.jsreact-springreact-three-fiber

React-three-fiber with react-spring animations


sorry if this seems like an obvious answer, but I am trying to create an animation similar to this. I am trying to create one similar with react-three-fiber but I can't use the ones shown in the docs since they manipulate the style transform property which isn't possible with three.js. I have tried to manipulate it through the position attribute and props but it comes with an error as shown here and I don't really know where to start to fix this. Here is my code:

const props = useSpring({
    to: async next => {
      await next({ position: [100, 100, 100] });
      await next({ position: [50, 50, 50] });
    },
    from: { position: [100, 100, 100] },
    config: { duration: 3500 },
    reset: true
  });

 return (
    <Canvas>

      <a.group {...props}>
        <Box position={[-1.2, 0, 0]} />
        <Box position={[1.2, 0, 0]} />
      </a.group>
    </Canvas>

)

I have used react-spring successfully with hovering and scale but it just doesn't work when using position.


Solution

  • i think something like that is best done with trigonometry

    const ref = useRef()
    useFrame(() => {
      ref.current.position.y = Math.sin(state.clock.getElapsedTime()) * 10
    })
    return <group ref={ref}> ...
    

    Math.sin will yield a value between -1 to 1 and alternates smoothly between the two. multiply your factor (the distance) and you have it. here's an example that dollies the camera like that: https://codesandbox.io/s/r3f-lod-e9vpx

    otherwise it's react-spring/three, not react-spring: https://codesandbox.io/s/clever-bartik-tkql8