Scaling a model to fit the screen

I’ve googled this, but maybe the solutions I’ve gotten don’t fit my issue, because they’re definitely not working correctly.

I have a cube that’s directly in front of the camera. I want to scale the X and Y to fill out the screen. I tried getting the distance of the camera (Z) to the front of the cube and then multiplying the distance but that didn’t work. It was close, but the cube was too big at close range and too far at long distance.

For perspective camera the size of the object required to fill top to bottom goes as a function of the sine of the field of view times the +Z distance from camera to abeam the nearest portion of the model, probably times some constant such as 2 (FOV is only half of the real up/down angle of view).

For ortho basically orthosize is half the height of the camera, so that’s super-easy, but it sounds like you have a perspective camera in your setup. Ortho camera view won’t change in size when the model is nearer/further.

Definitely times some constant. Probably such as 2.

1 Like

Yeah It’s perspective camera

Might be a bit hacky, but:

       private void OnGUI()
       {
           var min = camera.ViewportToWorldPoint(new Vector3(0f, 0f, distance));
           var minText = "Min: " + min.ToString("0.000");

           var max = camera.ViewportToWorldPoint(new Vector3(1f, 1f, distance));
           var maxText = "Max: " + max.ToString("0.000");

           GUI.backgroundColor = Color.black;
           GUI.contentColor = Color.white;
           GUI.Button(new Rect(20, Screen.height - 40, 200, 20), minText);
           GUI.Button(new Rect(Screen.width - 200, 20, 200, 20), maxText);
       }

min and max are world space positions of the camera frustum plane at z=distance. Use (max-min) to get the scaling values.

1 Like

+1 for using my favorite way of quickly getting info on the screen. :slight_smile: