Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
5

Vector3 to UDim2? [Discussion]

Asked by 9 years ago

What is a good practice to obtaining the position of an item in the 3Dimensional space and translating it into an X,Y UDim2 relative to your screen (Scale)?

The way I've done it with is by raycasting and taking the X/Y/Z relative to the cameras coordinateFrame. It's highly inaccurate [probably because I'm not implementing it correctly], and very messy.

I'd love some concepts on a more efficient manner of doing this.

1 answer

Log in to vote
4
Answered by 9 years ago

Stravant has a ScreenSpace module script which contains multiple functions for interactions between the 2D screen and the 3D environment. I'll give you the function from the module that deals with what you're asking for:

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.

Hope this helped!

Note: This only works if it's in a localscript. Also, the Vector2 will be the coordinates of the point from the top left corner of the screen, so if the gui is located in another gui that's offset from the (0, 0), the gui will be positioned incorrectly.

0
it doesn't work ;_; Bisoph 5 — 6y
Ad

Answer this question