I’ve got a bit of a problem with my viewport. I want it to have an object move from one side of the screen to the other (meaning i can’t just change the UI size), but it wouldn’t respect screen size. I don’t know how i would do this with a model, because it’s not 2D.
(The only way I would think you could get around this is making the ui the size as the object, then moving the UI based on where I wanted the object to move)
I have this code from an old project of mine where it calculates how large in studs the viewport (screen) is at a depth of 1 stud from the camera.
local vpY = math.tan(math.rad(CAMERA.FieldOfView * 0.5)) * 2
local vpX = vpY * (CAMERA.ViewportSize.X / CAMERA.ViewportSize.Y)
-- Multiplying these values by 'x' will give you the screen's stud size at 'x' depth
Maybe you can adapt this into your game to achieve the results you want. To help you get started, here’s a proof of concept script that shows a part fitted to the viewport’s borders:
Script
Paste this code in a new script and hit run.
-- Demo of displaying a part in front of the camera and fitting it within the viewport's borders.
-- Greenboo5
local CAMERA: Camera = workspace.CurrentCamera
----------------------------
-- Config
----------------------------
local mSizeBase = Vector3.new(7, 3, 1) -- Model size ratio (X, Y, Thickness).
local vpDepth = 10 -- How far in the camera the model's nearest face is (in studs).
----------------------------
-- Visuals
----------------------------
local TESTPART_SZ = Instance.new("Part", CAMERA)
TESTPART_SZ.Transparency = 1
TESTPART_SZ.Anchored = true
local SBOX = Instance.new("SelectionBox", TESTPART_SZ)
SBOX.Adornee = TESTPART_SZ
SBOX.LineThickness = 0.04
----------------------------
-- Behavior
----------------------------
game:GetService("RunService").PreRender:Connect(function()
-- Calculate the physical stud size of the viewport at a depth of 1.
local vpY = math.tan(math.rad(CAMERA.FieldOfView * 0.5)) * 2
local vpX = vpY * CAMERA.ViewportSize.X / CAMERA.ViewportSize.Y
-- Calculate scale for the model to 'fit' within the viewport at the given depth.
local mScale = vpDepth * math.min(
vpX / mSizeBase.X,
vpY / mSizeBase.Y
)
TESTPART_SZ.Size = mSizeBase * mScale
TESTPART_SZ.CFrame = CAMERA.CFrame * CFrame.new(0, 0, -vpDepth - TESTPART_SZ.Size.Z * 0.5) -- Apply offset from camera so that the nearest face is at vpDepth.
end)