Search code examples
three.js3dreact-three-fiber

Setting up rotation of a 3D object in front of camera in React Three Fiber


I'm having an issue with setting up rotation of a 3D gun model in React Three Fiber. The model is fixed in front of camera. The position updates correctly, the model is copying the moves of camera, but when it comes to rotation - horizontal rotation seems to be working well, when I move the mouse left or right, the model follows properly - vertical rotation however seems to be moving the object away (mouse direction up) or zooming it in (mouse direction down), although the model position doesn't really change.

I'm using the camera.quaternion to copy the camera movement and apply it to the object.

gunRef.current.position.set(
      camera.position.x, 
      camera.position.y + 1.5, 
      camera.position.z
      );
gunRef.current.quaternion.copy(camera.quaternion);

Do you have any idea how to fix this? Am I suppose to recalculate the model position based on rotation dynamically, or is there maybe any easier way to do it properly?

Sandbox: https://codesandbox.io/s/optimistic-moon-4cm0k5?file=/src/ui/BaseCharacter.js:2546-2720 (the dot point is irrelevant at this stage)


Solution

  • Okay, I just added the 3D model as a camera child, and then the camera to the scene. It works.

    if (gunRef.current) {
          camera.add(gunRef.current);
          scene.add(camera);
        }