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.
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
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!