How to calculate the correct distance from the camera to an object so it entirely fits the camera frame?

In my game, there will be some objects, which, when the player clicks on one, the camera must adjust to focus on the entire object, such as zoom, so that the object occupies the entire screen, without clipping.

In this example, I have these 3 objects, each one with a different shape and size:

When the user clicks one, I want to calculate the camera.CFrame so the camera can FIT the entire object.
I know the default camera.FieldOfView = 70.
So I have just to calculate the DISTANCE from the camera to the selected object (It is similar to press F in the 3D editor to bring the selected object):



How can I calculate the distance from the camera to the object to achieve this?

Why don’t you just change the camera’s CFrame to a position that fits whatever you are trying to do instead of trying to calculate the distance.

If you wanted to calculate distance you could use a ray, however like TooMuchRice said, you could also just cframe it to the object and then * offset.

It’s not an exact science but there’s a simple ways to go about it.

Take the longest length of the object by finding the maximum of the object’s x, y, and z size lengths.

Since the camera angle is 70, there is a simple trig formula to find the distance.

Distance = (maxLength*0.5)/math.tan(math.rad(35))

And that’s the bare minimum you’d technically need.

5 Likes

That’s what I’m talking about. Thanks @pheonixmario!

hey, how could i do this just so that the camera is looking straight down at the object?
example:
for an object of size 20, 5, 1 the cameras cframe would be:
(0, [calculated distance], 0) (0, -90, 0)

(i just noticed when i sent it that this was 4 years ago… im not expecting a reply anymore but ill leave this here :D)

You’re already given the distance here. It’s more of a radius so you can use that value for any camera angle.

let maxLength = 20 since you’ve specified your part size here.

To look straight down you could use CFrame.new() or CFrame.lookAt()

-- 1st parameter, the position of the camera
-- 2nd parameter, the position the camera aims at
Camera.CFrame = CFrame.new(targetPart.Position + Vector3.new(0,Distance, 0), targetPart.Position)

yeah i tried it and it didnt work, maybe i did something wrong, ill try to re-write it and see if it works

yeah idk, i re-wrote it and it still doesnt work, this is my code:

local biggestAxis = math.max(mainSize.X,mainSize.Y,mainSize.Z)
local distance = (biggestAxis*0.5)/math.tan(math.rad(35))+5
view_cam.CFrame = CFrame.lookAt(Vector3.new(0,distance,0),mainCf.Position)

(only thing i really changed is that i added an offset of +5 to the calculation to make it not totaly zoomed in)

wait shi- … im stupid, i thought the whole thing was in brackets but im adding 5 to the math.tan so im deviding by five more than i should… yeah that would explain it
nvm, it still doesnt work