Objective: Move the camera position ONLY on the Z axis so the frustrum fit 2 objects.
Conditions:
- One of the objects will be allways aligned with the camera X position
- Camera is set on perspective mode, not ortographic.
- the 2 spheres have no parent
The result seen in ortographic mode from top-view should look like this:
What I've done so far:
Using trigonometry this can be seen it as:
Knowing that, the objective is to find the Adjacent side, which will be the distance between the camera and the black point that will still fit the yellow one.
TECHNICALLY this piece of code should find the adjacent value:
private float CalculateMaxZoomDistanceToBall()
{
//Calculate angle from camera, should be divided of 2 cause it's placed on the middle of the line
Camera currentCamera = cameraComp;
angleDegrees = currentCamera.fieldOfView / 2; //(degrees)
//pass the angle to radians
angleRadians = angleDegrees * Mathf.Deg2Rad;
//Calculate the SinAngle
sinAngle = Mathf.Sin(angleRadians);
//Calculate Opposite
opposite = Mathf.Abs(blackPoint.transform.localPosition.x - yellowPoint.transform.position.x);
//Calculate hypotenuse
hypotenuse = opposite / sinAngle;
//Calculate CosX
cosAngle = Mathf.Cos(angleRadians);
//Calculate adjacent distance
adjacent = cosAngle * hypotenuse;
return adjacent;
}
as the camera object is positioned at 0, I simply add the return value to the gameObject.transform.position.z
And someone could say "but this is looking for the vertical FOV, you need the horizontal one", okey, I've also tried with the horizontal one, finded with:
float vFOVrad = currentCamera.fieldOfView * Mathf.Deg2Rad;
float cameraHeightAt1 = Mathf.Tan(vFOVrad * 0.5f);
float hFOVrad = Mathf.Atan(cameraHeightAt1 * currentCamera.aspect) * 2;
hFOV = hFOVrad * Mathf.Rad2Deg;
And it's not working, in some cases the camera position is to far of the espected position, sometimes it fits well and others it just goes to close.
Any help will be apreciated, thank you.