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 10 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 10 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:

01local M = game.Players.LocalPlayer:GetMouse()
02local Cam = game.Workspace.CurrentCamera
03 
04function WorldToScreen(Pos) --This function gets a World Position (Pos) and returns a Vector2 value of the screen coordinates
05    local point = Cam.CoordinateFrame:pointToObjectSpace(Pos)
06    local aspectRatio = M.ViewSizeX / M.ViewSizeY
07    local hfactor = math.tan(math.rad(Cam.FieldOfView) / 2)
08    local wfactor = aspectRatio*hfactor
09 
10    local x = (point.x/point.z) / -wfactor
11    local y = (point.y/point.z) /  hfactor
12 
13    return Vector2.new(M.ViewSizeX * (0.5 + 0.5 * x), M.ViewSizeY * (0.5 + 0.5 * y))
14end
15 
16local Vec2 = WorldToScreen(Vector3.new(0, 50, 0)) --Replace Vector3.new(0, 50, 0) with whatever vector3/position you want
17 
18Gui.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 — 7y
Ad

Answer this question