Reputation: 174
I'm new to Threejs and react-three-fiber. How to lock an object in canvas ( lock position, rotation ) when the perspective camera rotates and move. I want to make an object that avoids perspective camera movements and remain in a fixed position
Upvotes: 2
Views: 4615
Reputation: 786
You can use refs to access underlying objects, and thus modify their position, rotation, etc.
As PerspectiveCamera is an Object3D, you can add this mesh as a child so that they move together.
import { useRef } from 'react';
import { useThree } from '@react-three/fiber';
const MyMesh = () => {
const { camera } = useThree();
const ref = useRef();
useEffect(() => {
// Add mesh to camera
const meshRef = ref.current;
camera.add(meshRef);
// Cleanup on unmount
return () => {
camera.remove(meshRef);
};
}, [camera, ref.current]);
return <mesh ref={ref} position={[0, 0, -5]} />;
};
Here, I'm accessing Fiber's camera through its context via the useThree
hook.
Alternatively, you can copy the camera's properties every frame and apply an offset. This will result in the same display behavior.
You can access the renderloop via the useFrame
hook. This runs inside three, so there's no overhead within React. It's notable that you can access Fiber's context from within the hook's callback as well.
import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
const MyMesh = () => {
const ref = useRef();
useFrame(({ camera }) => {
// Move mesh to be flush with camera
ref.current.position.copy(camera.position);
ref.current.quaternion.copy(camera.quaternion);
// Apply offset
ref.current.translateZ(-5);
});
return <mesh ref={ref} />;
};
Upvotes: 4