I’m trying to make a script where a npc chases the player. I’m still learning about pathfindingserviece, so I won’t understand to much
local Torso = script.Parent.Torso
local main = script.Parent.Zombie
local PathfindingService = game:GetService("PathfindingService")
local function findTarget()
local distance = 200
local target = nil
for i,v in pairs(game.Workspace:GetChildren()) do
local humanoid = v:FindFirstChild("Humanoid")
local rootPart = v:FindFirstChild("HumanoidRootPart")
if humanoid and Torso and v ~= script.Parent then
if (Torso.Position - rootPart.Position).magnitude < distance then
distance = (Torso.Position - rootPart.Position).magnitude
target = rootPart
end
end
end
return target
end
while wait() do
local find = findTarget()
if find then
local path = PathfindingService:CreatePath()
path:ComputeAsync(Torso.Position, find.Position)
local waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
main:MoveTo(waypoint.Position)
end
main:MoveTo(find.Position)
end
end