What is the best way to serialize (or save or marshal) the state of the camera in a ThreeJS scene, and then un-serialize (or load or unmarshal) the camera later?
Right now I am saving the x, y, z coordinates of the camera's position, up, and (Euler angle) rotation fields. Later I try to restore this camera with calls to position.set()
, up.set()
, and rotation.set()
, and then follow-up with a call to updateProjectionMatrix()
. I assume the default Euler angle rotation order is the same when serializing and un-serializing.
Is this correct?
I would suggest instead storing the camera's matrix. This encompasses the entire transformation on the camera, including position, rotation and scaling.
Serializing:
const cameraState = JSON.stringify(camera.matrix.toArray());
// ... store cameraState somehow ...
Deserializing:
// ... read cameraState somehow ...
camera.matrix.fromArray(JSON.parse(cameraState));
// Get back position/rotation/scale attributes
camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With