I have a Baldi NPC that always goes to the players location. I’ve tried so many things, and yet, Baldi keeps stuttering and lagging. How do I fix this? Here’s the code and the example.
local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = Pathfinding:CreatePath({
AgentHeight = 2;
AgentRadius = 0.1;
AgentCanJump = false;
Costs = {
Water = 100;
DangerZone = math.huge
}
})
local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function findTarget()
local maxDistance = 10000 --The farest away distance that the "Zombie" starts to follow a player
local nearestTarget
for index, player in pairs(Players:GetPlayers()) do
if player.Character then
local target = player.Character
local distance = (Character.HumanoidRootPart.Position - target.HumanoidRootPart.Position) .Magnitude
if distance < maxDistance and target.Humanoid.Health > 0 then
nearestTarget = target
maxDistance = distance
end
if distance < 4 and nearestTarget then
nearestTarget.Humanoid:TakeDamage(100)
end
end
end
return nearestTarget
end
local function followPath(destination)
local success, errorMessage = pcall(function()
path:ComputeAsync(Character.PrimaryPart.Position, destination)
end)
if success and path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
if blockedWaypointIndex >= nextWaypointIndex then
blockedConnection:Disconnect()
followPath(destination)
return
end
end)
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex] .Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
return
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex] .Position)
else
warn("path not found")
return
end
end
for _, object in script.Parent:GetDescendants() do
if object:IsA("BasePart") then
object:SetNetworkOwner(nil)
end
end
while task.wait() do
local target = findTarget()
if target then
followPath(target.HumanoidRootPart.Position)
end
end