So i making a npcs that follows players, and i using collection service and pathfinding service. I think, npcs is going to old player position. I don`t know how to fix it, please help.
- Here a video(sorry about lags):
- Explorer screen:
- Script:
local Tags = game:GetService("CollectionService")
local pathfindingService = game:GetService("PathfindingService")
function findNearestTorso(pos,npc)
local list = game.Workspace:GetChildren()
local torso = nil
local dist = 10000
local temp = nil
local human = nil
local temp2 = nil
for x = 1, #list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= npc) and (temp2.Name ~= "Zombie") then
temp = temp2:findFirstChild("HumanoidRootPart")
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
function pathfind2(Target,Hum,hroot)
local enemytorso = Target
local human = Hum
local direct = Vector3.FromNormalId(Enum.NormalId.Back)
local ncf = hroot.CFrame * CFrame.new(direct)
local connection;
direct = ncf.p
local path = pathfindingService:CreatePath()
path:ComputeAsync(direct,enemytorso.Position)
local waypoint = path:GetWaypoints()
for index, WayPoint in ipairs(waypoint) do
human:MoveTo(WayPoint.Position);
-- if index > 2 then return end
end
end
function getHumanoid(model)
for _, v in pairs(model:GetChildren()) do
if v:IsA'Humanoid' then
return v
end
end
end
function setupNpc(npc,target)
npc.HumanoidRootPart:SetNetworkOwner(nil)
local zombie = npc
local human = getHumanoid(zombie)
local hroot = zombie.HumanoidRootPart
if target ~= nil then
pathfind2(target,human,hroot)
end
end
function cleanupNpc(npc)
--free resources used by the NPC
end
--Tags:GetInstanceAddedSignal("NpcAI"):Connect(setupNpc)
--Tags:GetInstanceRemovedSignal("NpcAI"):Connect(cleanupNpc)
--for _, tagged in Tags:GetTagged("NpcAI") do
-- setupNpc(tagged)
--end
while true do
wait()
for _, tagged in Tags:GetTagged("NpcAI") do
local target = findNearestTorso(tagged.HumanoidRootPart.Position,tagged)
setupNpc(tagged,target)
end
end