I’m pretty new to r3f and ThreeJS in general, I’m trying to achieve an effect where the camera starts on the outside of the model at [0,50,50]
for instance, then animates to the centre of point at [0,20,0]
. From here it will be able to spin around the centre point and look at different points on the model which is a ring around it. I have got the position animation down but for some reason I cannot figure out how to change the rotation/lookAt value (im not even 100% on which one I should be using), it always seems to be set to [0,0,0]
.
You’ll see at the start i’m logging the positon and rotation to see where the camera is, this returns correct values that i’ve used to test it like [30,0,0] just to offset it and get a different results but there is no visible change. I feel like this is something I’m either approaching wrong or missing a trick here. Eventually I want to add in mouse tracking to look around but I seem to be running into a similar issue where nothing is updated despite values being logged.
import { useThree, useFrame } from '@react-three/fiber';
import { OrbitControls, PerspectiveCamera } from '@react-three/drei';
import gsap from 'gsap';
import * as THREE from 'three';
function CameraController({ rotation, lookAtPosition, shouldAnimate, onAnimationComplete }) {
const cameraRef = useRef();
const controlsRef = useRef();
const { set } = useThree();
useEffect(() => {
const lookAtVector = new THREE.Vector3(lookAtPosition);
cameraRef.current.lookAt(...lookAtVector);
console.log(cameraRef.current.position);
console.log(cameraRef.current.rotation);
}, []);
useEffect(() => {
if (cameraRef.current) {
set({ camera: cameraRef.current });
const lookAtVector = new THREE.Vector3(...lookAtPosition);
cameraRef.current.lookAt(lookAtVector);
cameraRef.current.updateProjectionMatrix();
console.log(cameraRef.current.rotation);
}
}, [set, lookAtPosition]);
useEffect(() => {
if (shouldAnimate && cameraRef.current) {
gsap.to(cameraRef.current.position, {
duration: 2,
x: 0,
y: 20,
z: 20,
ease: 'power2.out',
onUpdate: () => {
cameraRef.current.updateProjectionMatrix();
},
onComplete: () => {
const lookAtVector = new THREE.Vector3(0, 20, 20);
cameraRef.current.lookAt(lookAtVector);
cameraRef.current.updateProjectionMatrix();
console.log(cameraRef.current.rotation);
if (onAnimationComplete) onAnimationComplete();
},
});
}
}, [shouldAnimate, onAnimationComplete]);
useFrame(() => {
if (controlsRef.current) {
controlsRef.current.update();
}
});
return (
<>
<perspectiveCamera ref={cameraRef} position={[0,25, 0]}/>
{cameraRef.current && (
<OrbitControls
ref={controlsRef}
args={[cameraRef.current]}
enableZoom={false}
enablePan={true}
enableRotate={true}
minDistance={10}
maxDistance={100}
dampingFactor={0.2}
rotateSpeed={0.5}
/>
)}
</>
);
}
export default CameraController;