Need Help Finding the Nearest NPC

Hello,

I need to determine the position of the closest NPC to a part, and I’m not sure where to start. The script needs to determine the closest NPC in a folder, then return the position value of the NPC’s HumanoidRootPart; but I can’t figure out how to find the nearest NPC.

Any help or pushes in the right direction would be greatly appreciated.

Start at the folder. Cycle through all NPCs, get the distances to the part, find the shortest. When you are done you only have the closest.

Thanks, but I’m not exactly sure how to do this. Could you point me in the right direction as to how to find the NPC’s distance from the part?

It would look something like this: Don’t copy and paste this code, this is just to give you an idea of the logic. The logic was also well explained by GolgiToad. I just though I’d put it in a script form for you.

local folder = game.Workspace:FindFirstChild("Folder")
local part = game.Workspace:findFirstChild("Part")


local function FindNearestNPC()
	local shortestDistance = math.max()
	local closestHRP = nil
	
	for _, npc in pairs(folder) do
		local hrp = npc:FindFirstChild("HumanoidRootPart")
		local dis = (hrp.Position - part.Position).Magnitude
		if dis < shortestDistance then
			shortestDistance = dis
			closestHRP = hrp
		end
	end
	
	return closestHRP.Position
	
end

Magnitude (roblox.com)

Last example is the distance between 2 positions.

Thanks, this helped. I have very little programming experience so it was helpful to see what the code could potentially look like.

1 Like

I think I understand what you meant now, thanks.

1 Like

I’m still pretty new to lua too, but not programming in general. I find if I cant logic through the steps, I can’t program it at all. Once I know the steps, its a matter of searching and reading. Usually, that “thing” you want to do has been done before.

If you haven’t yet, learn how to use your output window to your advantage. You will be doing a lot of trial and error to start.

Only a few months in, and it’s already getting faster for me! Hang in there!

2 Likes

I’m pretty sure others have already said this, but try magnitude it’s fairly easy to use and i’d say it’s fairly reliable

1 Like