I am trying to make a pathfinding ai that can become faster at random intervals. However, if I try to change the walkspeed, it starts stuttering, despite it working perfectly normally if it was set to that before actually testing. This makes it so that the boost isn’t as fast as it was intended to be, and instead just a slightly faster version of the AI.
I tried looking to find a reason as to why this happens but I can’t seem to find any, and i’ve tried a ton of solutions.
The AI is 2 seperate scripts, 1 in the NPC and 1 in ServerScriptService, which answers for pathfinding.
-- Module script in serverscriptservice
local pathService = game:GetService("PathfindingService")
local pathFinding = {}
function pathFinding.moveTo(ai, position)
local humanoid = ai:FindFirstChild("Humanoid")
local humanoidRootPart = ai:WaitForChild("HumanoidRootPart")
local path = pathService:CreatePath()
local success, err = pcall(function()
path:ComputeAsync(humanoidRootPart.Position, position)
end)
if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
local index = 2
humanoid:MoveTo(waypoints[2].Position)
local finish = humanoid.MoveToFinished:Connect(function(certificate)
if certificate and index < #waypoints then
index += 1
humanoid:MoveTo(waypoints[index].Position)
end
end)
--[[for i,v in pairs(waypoints) do
waypointd = Instance.new("Part")
waypointd.Size = Vector3.new(1,1,1)
waypointd.Anchored = true
waypointd.Position = waypoints[i].Position
end]]
end
end
return pathFinding
--Script in the npc
local pathFind = require(game:GetService("ServerScriptService"):FindFirstChild("PathFinding"))
local AI = script.Parent
local humanoidRootPart = script.Parent.HumanoidRootPart
local humanoid = script.Parent.Humanoid
humanoidRootPart:SetNetworkOwner(nil)
task.spawn(function()
while task.wait(math.random(700,1300)/100) do
humanoid.WalkSpeed = 36
task.spawn(function()
task.wait(3.5)
humanoid.WalkSpeed = 16
end)
end
end)
while task.wait(0.05) do
local targetPlayer = nil
local distance = 5000
for i,v in pairs(game:GetService("Players"):GetPlayers()) do
if v:IsA("Player") then
if v.Character then
if v.Character.Humanoid.Health >= 1 then
newDistance = (v.Character:WaitForChild("HumanoidRootPart").Position - humanoidRootPart.Position).Magnitude
if newDistance <= distance then
distance = newDistance
targetPlayer = v.Character
end
end
end
end
end
if targetPlayer ~= nil then
pathFind.moveTo(AI,targetPlayer.PrimaryPart.Position)
end
end