I have this code to make an NPC chase players, and it works but
lags very badly. Does anyone now how to help with this?
local PS = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")
local players = game:GetService("Players")
local zombie = script.Parent
local humanoid = zombie:WaitForChild("Humanoid")
function chase(plrRoot)
--print("chase function fired")
local point = plrRoot.Position
local path = PS:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentJumpHeight = 10,
AgentMaxSlope = 45,
})
local success, errorMessage = pcall(function()
path:ComputeAsync(zombie.HumanoidRootPart.Position, point)
end)
if success and path.Status == Enum.PathStatus.Success then
print("success")
for _, waypoint in pairs(path:GetWaypoints()) do
humanoid:MoveTo(waypoint.Position)
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end
humanoid.MoveToFinished:Connect(function()
print("moveto finished")
end)
end
else
warn("The path has unsuccessfully been created", errorMessage)
end
end
RunService.Heartbeat:Connect(function()
--print("hearbeat")
for _, player in pairs(players:GetChildren()) do
--print(player.Name)
if not player.Character then
break
end
local plrRoot = game.Workspace:FindFirstChild(player.Name).HumanoidRootPart
if plrRoot then
--print(player.Name, "plrRoot found")
end
--print((plrRoot.Position - zombie.PrimaryPart.Position).Magnitude)
if plrRoot and (plrRoot.Position - zombie.PrimaryPart.Position).Magnitude <= 25 then
--print("chasing", player.Name)
chase(plrRoot)
end
end
end)
I’m desperate please someone anyone I just need to know how to optimize this