I am trying to make a zombie NPC which follows the player. The NPC works fine when there are no obstacles between the NPC and the player, where PathFindingService is not used. However the NPC starts to stutter when it runs the pathfinding code. Here is a video of the issue and the corresponding code:
robloxapp-20221230-2147010.wmv (2.8 MB)
function PathFinding(target)
local path = game:GetService("PathfindingService"):CreatePath()
path:ComputeAsync(zombie.HumanoidRootPart.Position,target.Position)
local waypoints = path:GetWaypoints()
for _,waypoint in ipairs(waypoints) do
if CheckForLineOfSight(target) == true then
repeat
zombieHumanoid:MoveTo(target.Position)
path.Blocked:Connect(function()
PathFinding(target)
end)
if target == nil or target.Parent == nil then break end
until CheckForLineOfSight(target) == false
break
else
zombieHumanoid:MoveTo(waypoint.Position)
zombieHumanoid.MoveToFinished:Wait(1)
end
end
end
while wait(0.1) do
local target = FindNearestTorso()
print(target)
if target then
PathFinding(target)
end
end