How to move a player (with camera) towards a target object until camera fill target object?

I'm trying to solve this 'algorithm' problem.

I have a player and a camera on it. I want to automatically move this player towards a target object and stop it when target object completely "fit" my camera.

So my question is : how can I find target Vector3 player position, and camera rotation (up/down) to perfectly "view" an object ?

Consider that my target objects are simple Box.

Thanks

Edit: X is the "right" transform.position to "full" see target object

• What does your code know about the shape or bounds of the object? Commented Feb 5, 2021 at 22:46
• My code know object and these object are simple: square or rectangle !! Commented Feb 5, 2021 at 23:07
• As in they're 2D objects with a SpriteRenderer or a BoxCollider2D? Commented Feb 5, 2021 at 23:18
• No , 3d object, and yes, i can put boxcollider Commented Feb 5, 2021 at 23:36

Disclaimer: I don't use Unity or C#. All Unity-specific information was obtained from the documentation and not tested.

The field of view angle (FOV) determines the ratio of an object's size to its distance from the camera.

First, take the FOV and divide it by 2 (to get the angle from center rather than edge-to-edge, which is necessary by the next step) and, if it is in degrees, convert it to radians.

Then take the tangent of the angle. The tangent function tells us the slope — the ratio of distance to sideways movement — corresponding to the angle. (Another interpretation of this is “if an object is 1 unit away from the camera, how big will it be on screen?”)

Then, take the size of the object in terms of its radius or the maximum distance from its origin to an edge (supposing that you want the object to be as big as possible while still fitting in the camera's frame), and divide it by the tangent.

float targetCameraDistance =