-
I am trying to make an enemy that would chase in specific area and would attack.
-
The problem is that npc while following me for some time starts to glitch/stutter
robloxapp-20230408-1637518.wmv (2.0 MB) -
I have read bunch of other forums and I think I know the problem npc creats too many paths and I dont know how to get rid off them or create less of them.
Here is the pathfinding script:
local Pathfinding = game:GetService ("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = Pathfinding:CreatePath({
AgentHeight = 6;
AgentRadius = 3;
AgentCanJump = true;
Costs = {
Water = 100;
DangerZone = math.huge
}
})
local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")
local Animator = humanoid:WaitForChild("Animator")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function findTarget ()
local maxDistance = 100
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
local distance1 = (target.HumanoidRootPart.Position - workspace.Mid.Position).Magnitude
if distance < maxDistance and distance1 < 24.8 then
nearestTarget = target
maxDistance = distance
else
end
if distance < 6 then
local Hit = Animator:LoadAnimation(script.Parent.Attack)
if nearestTarget:FindFirstChild("Humanoid") then
if nearestTarget ~= nil then
Hit:Play()
nearestTarget.Humanoid:TakeDamage (25)
wait(1)
end
end
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
print("b")
blockedConnection:Disconnect()
followPath(destination)
end
end)
if not reachedConnection then
print("not reached")
reachedConnection = humanoid.MoveToFinished:Connect(function(reacjed)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
print("c")
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
print("a")
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
while wait() do
local target = findTarget()
if target then
followPath(target.HumanoidRootPart.Position)
end
end
local npcRootPart = NPC.HumanoidRootPart
npcRootPart:SetNetworkOwner(nil)