Recently I was working on something that required fitting an arbitrary model into an arbitrary viewport frame. I looked around saw this was a pretty common question, so I figured I’d write up a module
The above links to a class that can be used in two ways.
The first is to calculate a fixed minimum distance that’s guaranteed to contain the model regardless of the camera orientation or viewport size.
This is useful as it’s a low-cost one-time calculation assuming you’re not constantly adding/removing/changing the model or viewport frame.
The second is to calculate a camera cframe that best fits the model given an orientation. This will mean that the model will always be touching at least one edge of the viewport frame.
However, it’s important to note that this calculation is based off of the model’s point cloud meaning meshes, csg, and/or any other base part that makes it difficult to get a proper point cloud may cause this calculation to seem inaccurate.
For example compare happy home vs piano in the above video
This is really nice and super useful for camera calculations, which is one of the trickier parts to nice UI design when working with models with varying sizes (unless you’re manually adjusting CFrame positions, and that can be a lot of manual work + very tedious).
Really nice resource, I will be sure to use this (in the next few days, since I was about to jump into some ViewportFrame usage)!
This is great, and so easy to setup and use. Your code base is very adaptable and sturdy, which is saying a lot. It’s a work of art, well done @EgoMoose.
You can use it to make a camera surround the model if you want:
Create a ScreenGui, any name
Create an ImageButton inside this ScreenGui
Right after that, add a LocalScript inside this ScreenGui
Then paste the script below
To add the object to the image, add a part inside the image button called: HandleView and right after Group In it and in all the models you want within the group, make sure that the part fits calls : “HandleView” is inside this group and the group is inside ImageButton
local Camera = Instance.new("Camera")
Camera.Parent = script.Parent
local ModelView = script.Parent.DivisionModel
local HandleView = ModelView.MainPart
while wait() do
Camera.CameraSubject = ModelView
script.Parent.CurrentCamera = Camera
for i = 0, 360 , 2 do
wait()
local cframe = HandleView.CFrame * CFrame.Angles(0,math.rad(i),0) * CFrame.new(0,2,-9)
Camera.CFrame = CFrame.new(cframe.p, HandleView.Position)
end
end
Definitely a lifesaver. There’s a post that suggests another solution, but it just didn’t work well for me. The minimum fit feature is amazing. Good job.