How to calculate an objects udim2 position on the screen

Hey there

I was wondering how you would calculate a objects position on the screen

Obviously i want to return it as a udim2

I guess there may be some calculation converting the two

Thanks

local M = game.Players.LocalPlayer:GetMouse()
local Cam = game.Workspace.CurrentCamera

function WorldToScreen(Pos) --This function gets a World Position (Pos) and returns a Vector2 value of the screen coordinates
    local point = Cam.CoordinateFrame:pointToObjectSpace(Pos)
    local aspectRatio = M.ViewSizeX / M.ViewSizeY
    local hfactor = math.tan(math.rad(Cam.FieldOfView) / 2)
    local wfactor = aspectRatio*hfactor

    local x = (point.x/point.z) / -wfactor
    local y = (point.y/point.z) /  hfactor

    return Vector2.new(M.ViewSizeX * (0.5 + 0.5 * x), M.ViewSizeY * (0.5 + 0.5 * y))
end

local Vec2 = WorldToScreen(Vector3.new(0, 50, 0)) --Replace Vector3.new(0, 50, 0) with whatever vector3/position you want

Gui.Position = UDim2.new(0, Vec2.X, 0, Vec2.Y) --Since the function doesn't return a UDim2 value, you have to create a Udim2 value and put the X and Y of the Vector2 into that UDim2.

You can also just use :WorldToScreenPoint

local cam = workspace.CurrentCamera
local point = cam:WorldToScreenPoint(Vector3)
local udim = UDim2.new(0, point.X, 0, point.Y)
1 Like