Calculating distance or FOV to accurately pixel size an object in perspective view

Ok I’ve been able to correctly size an orthographic camera to fit my object (because that’s easy :slight_smile: - but now I want to set either the FOV or preferably the distance of an object, from the camera to perfectly frame it using a perspective camera.

I’ve been trying to adapt @wolfram’s answer in With a perspective camera: Distance independent size gameobject - Questions & Answers - Unity Discussions but it’s not working for me.

Basically I have the height of an object in world units and need it to fill a render texture. Which mean I pretty much need to position it the right distance from the camera. (And also offset it for the fact that it’s modelled up from 0,0,0 - it’s a tree).

So let’s say that it’s world unit height is 4, what formula for distance do I have to use to place it infront of a camera (that’s rendering a 256 pixel high render texture) so that it fills the frame?

Turns out it was me messing up - the calculation is:

  var distance = 1/(2f * Mathf.Tan((float)Camera.main.fieldOfView /2 * Mathf.Deg2Rad)/(maxY-minY));

To render correctly for a 0,0,0 foot object it is necessary to capture up from the middle of the texture or the perspective is wrong.