I wrote an AI a while ago, but i just realized that sometimes when I go behind a wall, the AI pauses.
Here is the code:
local pathservice = game:GetService("PathfindingService")
local hum = script.Parent.Humanoid
local root = script.Parent:FindFirstChild("HumanoidRootPart")
local man = script.Parent
walking = false
root:SetNetworkOwner(nil)
local function walk()
local track = script.Parent.Humanoid.Animator:LoadAnimation(script.Parent.Humanoid.Animation)
if walking == false then
else
track:Play()
end
end
local function cansee(target)
local origin = root.Position
local direction = (target.Torso.Position - root.Position).unit *40
local ray = Ray.new(origin, direction)
local hit, pos = workspace:FindPartOnRay(ray, man)
if hit then
if hit:IsDescendantOf(target) then
return true
else
end
else
return false
end
end
local function findtarget()
local players = game.Players:GetPlayers()
local maxdist = 40
local nearesttarget
for i, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (root.Position - target.Torso.Position).Magnitude
if distance < maxdist and cansee(player.Character) then
if walking == true then
else
walking = true
walk()
end
nearesttarget = target
maxdist = distance
else
end
end
end
return nearesttarget
end
local function getpath(destiniation)
local PParams = {
["AgentHeight"] = 6,
["AgentRadius"] = 2,
["AgentCanJump"] = false
}
local path = pathservice:CreatePath(PParams)
path:ComputeAsync(root.Position, destiniation)
return path
end
local function attack(target)
local distance = (root.Position - target.HumanoidRootPart.Position).Magnitude
if distance > 2 then
hum:MoveTo(target.HumanoidRootPart.Position)
else
local attackanim = hum:LoadAnimation(script.Parent.SwingAnimation)
attackanim:Play()
wait(0.5)
target.Humanoid:TakeDamage(script.Parent:GetAttribute("Damage"))
end
end
local function walkto(destination)
local path = getpath(destination)
if path.Status == Enum.PathStatus.Success then
for index, waypoint in pairs(path:GetWaypoints()) do
local target = findtarget()
if target and target.Humanoid.Health > 0 then
attack(target)
break
else
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait()
end
end
else
hum:MoveTo(destination - (root.CFrame.LookVector * 10))
end
end
local function patrol()
local Wpoints = workspace["AI Waypoints"]:GetChildren()
local RNum = math.random(1, #Wpoints)
walkto(Wpoints[RNum].Position)
end
while wait(0.1) do
patrol()
end
and here is the video:
Let me know if you can help. Thanks.