I’m trying to achieve an AI that chases you until you reach high ground or are out of it’s range. Once you are out of range, the AI should run back to it’s original position using pathfinding service.
The issue is after awhile the AI bugs out and isn’t responsive. It still works, it just goes extremely slow. This issue is somehow reduced when I set the network ownership to nil. The problem with doing that is the AI can unfairly kill the player because it is using the server for physics.
The issue also becomes more common when multiple AI chase at the same time.
local ai = script.Parent
local speed = 20
local radius = ai.Config.Range.Value
local elevatedSurfaceDistanceThreshold = ai.Config.ElevatedSurfaceHeight.Value
local originalPosition = ai.HumanoidRootPart.Position
local movingback = false
ai.Humanoid.WalkSpeed = ai.Config.Speed.Value
--[[local children = ai:GetChildren()
for i,v in pairs(children) do
if v:IsA("Part") then
v:SetNetworkOwner(nil)
end
end]]
-- this is where i attempted changing the network ownership
local function getClosestPlayer()
local closestDistance = math.huge
local closestPlayer = nil
for _, player in ipairs(game.Players:GetPlayers()) do
local character = player.Character
local humanoid = character and character:FindFirstChildOfClass("Humanoid")
local distance = (character and character:FindFirstChild("HumanoidRootPart") and (character.HumanoidRootPart.Position - ai.HumanoidRootPart.Position).Magnitude) or math.huge
if distance <= radius and distance < closestDistance and humanoid and humanoid.Health > 0 and character.HumanoidRootPart.Position.Y <= elevatedSurfaceDistanceThreshold then
closestDistance = distance
closestPlayer = player
end
end
return closestPlayer
end
local computing = false
function MoveToPosition(position)
if computing == true then return end
computing = true
--ai.Humanoid.WalkSpeed = ai.Config.Speed.Value*2
local path = game:GetService("PathfindingService"):CreatePath()
path:ComputeAsync(ai.HumanoidRootPart.Position, position)
if Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for i, waypoint in ipairs(waypoints) do
ai.Humanoid:MoveTo(waypoint.Position)
if getClosestPlayer() then
computing = false
ai.Humanoid.WalkSpeed = ai.Config.Speed.Value
return
end
ai.Humanoid.MoveToFinished:Wait()
end
computing = false
ai.Humanoid.WalkSpeed = ai.Config.Speed.Value
else
computing = false
ai.Humanoid.WalkSpeed = ai.Config.Speed.Value
end
end
local function chasePlayer(dt)
local closestPlayer = getClosestPlayer()
if closestPlayer then
ai.Humanoid:MoveTo(closestPlayer.Character.HumanoidRootPart.Position)
else
MoveToPosition(originalPosition)
end
end
while task.wait(0.3) do
chasePlayer()
end
If there’s any ideas on why this is happening it would be really appreciated!