Bounds to Orthographic Fitting equalvant for Perspective Camera

Hi there,

I’m using following code from this place for Othographic camera to which works great

void Fit () {
        float screenRatio = (float)Screen.width / (float)Screen.height;
        float targetRatio = rink.bounds.size.x / rink.bounds.size.y;

        if(screenRatio >= targetRatio){
            Camera.main.orthographicSize = rink.bounds.size.y / 2;
        }else{
            float differenceInSize = targetRatio / screenRatio;
            Camera.main.orthographicSize = rink.bounds.size.y / 2 * differenceInSize;
        }
    }

However, now i want to get the same effect using perspective camera. Just like above code camera will not move.

Please advise
Thanks

If you calculate the height and distance to the target, the FOV is;

var fov = 2f * Mathf.Atan(targetHeight * 0.5f / targetDistance) * Mathf.Rad2Deg;

2 Likes

Thanks @grizzly for the assistance.

So targetHieght’d be rink.bounds.size.y?
and distance’d be like this?
Vector3.Distance(Camera.main.transform.position, rink.transform.position);

So final code’d be

var targetDistance = Vector3.Distance(Camera.main.transform.position, rink.transform.position);
var targetHeight = rink.bounds.size.y;
var fov = 2f * Mathf.Atan(targetHeight * 0.5f / targetDistance) * Mathf.Rad2Deg;

Is this right?

Yes, the frustum height should match the bounds height.