i am trying to update a stateful variable cameraPosition
using Typescript, React and Babylonjs.
this is the code snipped:
const camera = scene?.cameras[0];
const prevPositionRef = useRef<Nullable<Vector3>>(null);
const [cameraPosition, setCameraPosition] = useState<Vector3>(
new Vector3(0, 0, 0)
);
useEffect(() => {
if (camera) {
const onAfterInput = () => {
if (
!prevPositionRef.current ||
!prevPositionRef.current.equals(camera.position)
) {
console.log("change") //also logs every changed frame!
setCameraPosition(camera.position); // does not set the position (or does it?!)
prevPositionRef.current = camera.position.clone();
}
};
camera.onAfterCheckInputsObservable.add(() => {
// it correctly triggers every frame
onAfterInput();
});
return () => {
camera.onAfterCheckInputsObservable.removeCallback(() => {
onAfterInput();
});
};
}
}, [camera]);
console.log(cameraPosition) // does not log position!?
i even tried to listen to changes of cameraPosition by doing this:
useEffect(() => {
console.log("cameraPosition updated:", cameraPosition);
}, [cameraPosition]);
but no success.
there are 2 console.log() positions: the first one does log on every frame when the camera was changed correctly. the second one does not log the cameraPosition. and i just cannot figure out why. it seems the algorithm does not even realize that the cameraPosition changed.
What am i doing wrong here? i want to use cameraPosition in other components too.
any help would be great!
Thanks a lot!