In the script below I have some issues, especially when there are multiple players in the radius that the NPC should start chasing them, in this scenario the animation of walking and the movement itself become very jumpy and the NPC has a chance of just stopping dead in its tracks for no reason. Most of these issues don’t occur when there is only one player within the radius. This is my first time working with pathfinding and attempting to make an AI if you could even call it that so any help would be appreciated.
TLDR: script works however can become very buggy
local pathService = game:GetService("PathfindingService")
local pathFolder = game.Workspace:WaitForChild("Path")
local hum = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("Torso")
local path = pathService:CreatePath()
local RS = game:GetService("RunService")
local alreadyChasing = false
local StopPath = false
function chaseAfter(target)
StopPath = true
path:ComputeAsync(torso.Position,target.Position)
local waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait()
print((torso.Position - target.Position).Magnitude)
if (torso.Position - target.Position).Magnitude >= 25 then
StopPath = false
end
end
end
local function multiplePlayers(player)
while wait(0.01) do
if (torso.Position - player.Position).Magnitude <= 25 then
chaseAfter(player)
else
break
end
end
end
local function chase()
local first = true
local chosenPlr
local plrAmmount = 0
game.Workspace:WaitForChild("SoundParts"):WaitForChild("SoundChangeCave").Touched:Connect(function(hit)
if hit and hit.Parent:FindFirstChild("Humanoid") then
if first then
first = false
while wait(0.01) do
for i, player in pairs(game.Players:GetChildren()) do
if (torso.Position - game.Workspace:FindFirstChild(player.Name):FindFirstChild("HumanoidRootPart").Position).Magnitude <= 25 then
plrAmmount +=1
chosenPlr = player.Character:FindFirstChild("HumanoidRootPart")
if plrAmmount >= 2 then
multiplePlayers(chosenPlr)
else
chaseAfter(chosenPlr)
end
end
end
plrAmmount = 0
end
end
end
end)
end
task.spawn(chase)
local function pathFind()
path:ComputeAsync(torso.Position,pathFolder:FindFirstChild(math.random(1,4)).Position)
local waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
if StopPath == false then
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait()
else
repeat task.wait(0.5) until StopPath == false
pathFind()
end
end
pathFind()
end
pathFind()```