I have been trying to make an NPC that will pathfind to the closest player within a certain distance. The issue is the fact that everything I have attempted has failed.
I want to add a pathfinding service to this specific piece of code as it works best for my NPC:
local PositionTorso = script.Parent.Torso.Position
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 100
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("UpperTorso")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while wait(0.01) do
local target = findNearestTorso(PositionTorso)
if target ~= nil then
script.Parent.Random.Value = false
script.Parent.Hum:MoveTo(target.Position)
else
script.Parent.Random.Value = true
end
PositionTorso = script.Parent.Torso.Position
end
Problems
-
Walks into walls as it has no pathfinding service
-
The NPC stays behind the player at all times
Video Of Problem 2:
robloxapp-20230206-2059007.wmv (1.3 MB)
Can someone help me figure out a way to implement a pathfinding service into my code? I have attempted to watch tutorials and videos on how to do it but it just doesn’t work for me.
An idea I hade to fix problem 2 is to add 3-5 studs in front of me to make the NPC go to that part and not my torso.
HELP!!!