Search code examples
reactjsreact-three-fiberthreejs-editor

Moving an object by changing its position in useFrame does not work


I have a code as below. Although I update the sphere position with every frame (useFrame), it does not reflect on my scene. Can someone please help me understand why it will not work.

PS : I am new to this and am trying to do some quick proof of concepts.

function Marble() {
  const controls = useControls()
  const [sphereRef, sphereApi] = useSphere(() => ({
    type: "Dynamic",
    mass: 1,
    position: [0, 2, 0]
  }));

  
  //sphereApi.position.set([0,0,0])
  //console.log("SHM sphereAPI position", sphereRef.current.position);
  useFrame(() => {
    const { forward, backward, left, right, brake, reset } = controls.current
    if (forward == true) {
      console.log("sphereRef position", sphereRef.current.position);
      console.log("sphereAPI position", sphereApi.position);
      //console.log("model position", model.current.position)
      // sphereApi.velocity.set(2,2,2);
      sphereApi.position.set(5,0,0)
      // sphereRef.current.position.set(5,0,0);
    }
  })

  return (
    <mesh ref={sphereRef} castShadow>
      <sphereBufferGeometry attach="geometry" args={[1, 32, 32]}></sphereBufferGeometry>
      <meshStandardMaterial color="white" />
    </mesh>
  );
})

Solution

  • ( See it online: Stackblitz )

    Doing sphereApi.position.set(5,0,0) on every frame, just sets the sphere position to x=5 on every frame.

    So you should create a state first to store the x position, then update it on every frame to +=5, and then set the sphere position to it:

    const [sphereX, setSphereX] = useState(0);
    useFrame(() => {
      setSphereX((sphereX) => sphereX + 0.05); // set state x position to +0.05 (5 is fast)
      sphereApi.position.set(sphereX, 0, 0); // apply the state to the sphere position
    });
    

    Also make sure to use allowSleep={false} since changing position directly isn't a physical movement, so the physical scene may get sleep.

    Online: Stackblitz