Home > other >  How to stop useFrame afrer n seconds in react-three-fiber
How to stop useFrame afrer n seconds in react-three-fiber

Time:07-18

hi I have animation in useFrame which plays after click and I need to stop it after 2 seconds for example

  const [clicked, click] = useState(false)
  useFrame((state, delta) => (clicked ? group.current.rotation.x  = 0.01 : 
  group.current.rotation.x))

any advice? , thanks

CodePudding user response:

I made it work using the use-timer library (use-timer)

Use the useTimer hook:

  const { time, start, pause, reset, status } = useTimer();

Inside the useFrame, you decide when to rotate the cube:

useFrame(() => {
 if (status === "RUNNING") {
  boxRef.current.rotation.x  = 0.05;
 }

 if (status === "RUNNING" && time >= 2) {
  pause();
  reset();
 }
})

Clicking on the box starts the timer:

const handleClick = () => {
if (status === "PAUSED" || status === "STOPPED") {
  start();
}};

I am pretty sure you can do something with the state inside useFrame aswell, but that felt more complicated. (state.clock.elapsedTime)

  • Related