I tried to make npc follow player using pathfinding but somehow my code slowly gets lag harder and harder when you keep npc follow player.
What is problem here and how can I fix this?
local walk = true --if this is false, npc stops walking
pcall(function()
local function checkChanged(lastPos) --function to check if player moved after path check
if walk == false then
return true
else
if target then
if (lastPos - target.RootPart.Position).magnitude > 5 then --target moved
return true
else
return false
end
else
return true
end
end
end
while true do
if walk == true and target then
local lastPos = target.RootPart.Position
path:ComputeAsync(humanoid.RootPart.Position, target.RootPart.Position)
if path.Status == Enum.PathStatus.Success then
local wayPoints = path:GetWaypoints()
local moveChanged = false
coroutine.wrap(function() --this coroutine is problem I think
for ind, point in pairs(wayPoints) do
if moveChanged == true then --cancels coroutine if target moved
break
end
if point.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
if ind ~= 1 then --I ignored first waypoint since I thought first one is just npc's position
humanoid:MoveTo(point.Position)
humanoid.MoveToFinished:Wait()
end
end
wayPoints = nil
end)() --coroutine's end
while moveChanged == false do --wait until target moves (have to change path)
if checkChanged(lastPos) == true then
--print("target moved")
moveChanged = true --changing this true will stop coroutine's loop
break --break to go to next loop, get another path
end
game:GetService("RunService").Heartbeat:Wait()
end
end
else
game:GetService("RunService").Heartbeat:Wait()
end
end
end)