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

Trying to make UI that hovers over NPC?

Asked by 4 years ago

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!

0
Could use billboard GUI and set to render on top of everything. As for when the character is off screen not sure how you could do that. Benbebop 1049 — 4y
0
See that's what I thought of first too. But indeed you can't make it work when the NPC is off screen then. This code actually works fine, but I just don't know when to put it on the right or left side of the screen when the npc is off screen. blacksmiley0 19 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

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)
Ad

Answer this question