I followed a tutorial for a pathfinding AI, but there is a problem with it. When the AI can’t find a path it will stop in its tracks until one can be computed. I haven’t used pathfinding much, so I just need an idea of how to make it not do this.
Here’s the script for the AI. It’s pretty basic, but I’d assume I just need to find out a way to make it find a new path when one is not computed? Anyways thanks for the help.
local Pathfinding = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = Pathfinding:CreatePath({
AgentHeight = 6;
AgentRadius = 3;
AgentCanJump = false;
Cost = {
Water = 100;
DangerZone = math.huge
}
})
local Character = script.Parent
local humanoid = Character:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local attackAnim = script.Attack
local attackAnimTrack = humanoid:LoadAnimation(attackAnim)
local function findTarget()
local maxDistance = 50000
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 then
nearestTarget = target
maxDistance = distance
end
if distance < 5 then
if nearestTarget.Humanoid.Health > 0 then
nearestTarget.Humanoid:TakeDamage(25)
attackAnimTrack:Play()
script.Parent.HumanoidRootPart.Swing:Play()
if nearestTarget.Humanoid.Health <= 0 then
game.ReplicatedStorage.Jumpscare:FireClient(player)
end
wait(math.random(0.75, 1))
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
blockedConnection:Disconnect()
followPath(destination)
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()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
end
end
while wait() do
local target = findTarget()
if target then
followPath(target.HumanoidRootPart.Position)
end
end