I'm trying to make a UI that hovers over an NPC, so you always know where he is. I tried using Camera:WorldToScreenPoint for this. Now whenever the NPC is not on screen I would want the UI to be on the far left/right side of the screen, depending on which is closest to the NPC. However this is where my code fails and I don't know what to do.
Code:
while wait() do local vector, onScreen = camera:WorldToScreenPoint(RexTorso.Position) --rex is the NPC if onScreen then -- NPC is onscreen script.Parent.Position = UDim2.new((vector.X-100)/mouseX, 0, (vector.Y-100)/mouseY,0) -- this works fine else if vector.X < 0 or vector.X < mouseX then -- NPC is on the left side of the view -- this is where the issue is script.Parent.Position = UDim2.new(0, 0, (vector.Y-100)/mouseY, 0) else --right side of the view script.Parent.Position = UDim2.new(1 - 200/mouseX, 0, (vector.Y-100)/mouseY, 0) end end end
Thanks in advance!
I've found the solution to this, so I'll close this question.
For those wondering, this is the code:
local function camchanged() local v, onScreen = camera:WorldToScreenPoint(RexTorso.Position) local xScale = v.X/l_x local yScale = v.Y/l_y local depth = v.Z local yoffset = 550/(depth^(2/3)) if onScreen then -- rex is onscreen script.Parent.Position = UDim2.new(xScale, 0, math.max(0, yScale-yoffset/l_y), 0) else if -yoffset < 0 then script.Parent.Position = UDim2.new(math.clamp(xScale, 0, 1), 0, math.clamp(yScale-yoffset/l_y, 0, 1), 0) last_y = math.clamp(yScale, 0, 1) else script.Parent.Position = UDim2.new(math.clamp(1-xScale, 0, 1), 0, last_y, 0) end end end workspace.CurrentCamera.Changed:Connect(camchanged) workspace.Rex.Head.Changed:Connect(camchanged)