Search code examples
three.jsreact-three-fibercannon.js

Can change position of a mesh using useRef but not with Cannon.js in React-Three-Fiber


When I use useRef for access a mesh, I can change its position as this:

const [boxRef] = useRef();
...
boxRef.current.position.setX(boxRef.current.position.x + 1);

And it works! But when I use useBox from Cannon.js to give it a physic, it doesn't:

const [boxRef] = useBox(() => ({
  mass: 1,
  position: [0, 4, 0],
  velocity: [0, 1, 0],
}));
...
boxRef.current.position.setX(boxRef.current.position.x + 1);

Solution

  • Use the second argument of useBox:

    const [boxRef, boxApi] = useBox(() => ({
      mass: 1,
      position: [0, 4, 0],
      velocity: [0, 1, 0],
    }));
    ...
    boxApi.position.set(-2, 0, 0);