I want to keep a point in the scene in the same screen position after changing the field of view, but can't work out which angles to rotate the camera afterwards.
This is fairly straightforward.
You know:
- What point on screen the point in space occupied before the FOV change.
- Where that point on screen is after the FOV change.
How to work it out:
- Store where the object was on screen and the direction to that point from the camera's projection.
- Perform the FOV change.
- Transform the direction of the desired screen point to the stored direction.
The code:
function changeFieldOfView(newFieldOfView : float, target : Transform) {
if(newFieldOfView) {
if(target) {
//The point on screen
var viewportPoint : Vector3 = camera.WorldToViewportPoint(target.position);
//The direction to the point in space from the point on screen
var to : Vector3 = camera.ViewportPointToRay(point).direction;
//Change the FOV
camera.fieldOfView = newFieldOfView
//The new direction from the point on screen
var from : Vector3 = otherCamera.camera.ViewportPointToRay(point).direction;
//Rotate the camera
camera.rotation *= Quaternion.FromToRotation(from, to);
}
else camera.fieldOfView = newFieldOfView; //Change the FOV
}
}