EldarGranulo
EldarGranulo

Reputation: 1615

Calculate camera target for orbit controls from given rotation and position of camera

I have the following issue when using orbit controls. I set the camera target to 0, 0, 0. Then after an AJAX call I set the camera position and rotation manually. After orbit controls update call, the rotation of the camera gets reset.

I have found that this happens because when the orbit controls update is called, the rotation of the camera is calculated from the camera position and the target of the orbit controls.

Is there some way to solve this?

Upvotes: 1

Views: 1190

Answers (1)

Brakebein
Brakebein

Reputation: 2237

I would save the distance between camera and target before applying transformation to camera. Afterwards, I would place the target in front of the camera with the respective distance.

var distance = new THREE.Vector3().subVectors(camera.position, controls.target).length();

// apply transformation - matrix, euler rotation, or quaternion?

var normal = new THREE.Vector3(0,0,-1).applyQuaternion(camera.quaternion);
// instead of quaternion, you could also use .applyEuler(camera.rotation);
// or if you used matrix, extract quaternion from matrix

controls.target = new THREE.Vector3().add(camera.position).add(normal.setLength(distance));

EDIT: Could you additionally explain why in the calculation of normal you use vector (0, 0, -1)?

In computer graphics, the local coordinate system of a camera is usually that positive x-axis is pointing to the right, the positive y-axis is pointing up, and hence the direction you are looking at is negative z-axis. For the calculation above, I needed the direction the camera is looking to - from local space (0,0,-1) to world space (0,0,-1).applyQuaternion().

enter image description here

Upvotes: 3

Related Questions