I'm trying to make a game, the AI enemy is programmed to go to a random part position in a folder in the workspace and attack a player once they are enough distance away, but when the enemy gets close to my player, the AI stutters, basically stopping for a bit, then starting, then stopping, rinse and repeat. Any help? Here's the script..
local reaper = script.Parent
local humanoid = reaper.Humanoid
reaper.PrimaryPart:SetNetworkOwner(nil)
local PathfindingService = game:GetService("PathfindingService")
local function findTarget()
local players = game.Players:GetPlayers()
local maxDistance = 40
local nearestTarget
for index, player in pairs(players) do
if player.Character then
local target = player.Character
local distance = (reaper.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance < maxDistance then
nearestTarget = target
maxDistance = distance
end
end
end
return nearestTarget
end
local function getPath(destination)
local pathParams = {
["AgentHeight"] = 5.45,
["AgentRadius"] = 3.757,
["AgentCanJump"] = false
}
local path = PathfindingService:CreatePath(pathParams)
path:ComputeAsync(reaper.HumanoidRootPart.Position, destination.Position)
return path
end
local function attack(target)
local distance = (reaper.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude
if distance > 1 then
humanoid:MoveTo(target.HumanoidRootPart.Position)
else
target.Humanoid.Health = 0
end
end
local function walkTo(destination)
local path = getPath(destination)
for index, waypoint in pairs(path:GetWaypoints()) do
local target = findTarget()
if target then
print("Attacking ", target.Name)
attack(target)
break
else
print("Moving to ", waypoint.Position)
humanoid:MoveTo(waypoint.Position)
humanoid.MoveToFinished:Wait()
end
end
end
local function patrol()
local waypoints = workspace.waypoints:GetChildren()
local randomNum = math.random (1, #waypoints)
walkTo(waypoints[randomNum])
end
while wait() do
patrol()
wait()
end
