Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing Camera State in ThreeJS

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?

like image 758
someben Avatar asked Mar 23 '15 22:03

someben


Video Answer


1 Answers

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); 
like image 146
Brendan Annable Avatar answered Sep 21 '22 17:09

Brendan Annable