Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Trying to make UI that hovers over NPC?

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!

2 comments

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.

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.

1 answer

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.