Math used to make SurfaceGui display like ScreenGui

If I have a part with a stud width of 1, what math would I use to determine the depth that the part would need to be set in front of the camera in order to make the part fit perfectly within the bounds of the screen?

Going to be used to display a surface gui with parts mixed in. I have a few ideas on how to go about this, but am hoping one of the many math wizards on here could help speed up the process :).

Even just a tip in the right direction would be incredibly helpful!

6 Likes

Bump! Anyone have some tips to point me in the right direction?

My current attempt was to try and use trig to figure out the part of the triangle shown in this diagram

Image from Gyazo

But I am unsure if this is how the camera Field of View works, and of the math I have been using.
I tried to use (part.Size.Y/2) / math.tan(cam FOV/2), but the way it’s acting is incredibly strange to me. It gives me a negative distance most of the time. Anyone know if it’s my math that’s wrong, or was it something with the way it was implemented?

2 Likes

Alright guys, I figured it out! Had to divide the angle by two for the tan function, and multiply it by two afterwards. Unsure of why, but hey, if it ain’t broke…

This is the math for the end result. This will position a part to fit itself within the camera bounds using the part’s size.Y. Obviously, if you want it to fit perfectly within the screen just let the size.X of the part be part.Size.Y*(cam.ViewportSize.X/cam.ViewportSize.Y).

local ang = math.tan(math.rad(cam.FieldOfView/2))
local camDist = part.Size.Y/(ang*2)

2 Likes

Don’t mean to bump but for anyone wondering why this is, it’s due to producing the right triangle in the image using half the field of view and half the part size.

tan(FOV/2) = (Part.Size.Y/2) / Distance
--> Distance = (Part.Size.Y/2)/(tan(FoV/2))

Why I’m here you might ask, well I was actually looking to do this myself except I tried to resize the part instead (it’s the same math either way, but I keep the surface gui resolution by resizing the part using pixels/stud mode). My issue for those who might come up on this thread was that FOV is vertical, so I needed to use the Size.Y instead of .X (yeah rip me ik)

1 Like