I've been working on a simple npc that uses PathfindingService and I've modified a code that someone else wrote, however, upon testing in studio, I noticed that the npc would move in a weird way, almost as if the place/or game was experiencing some lag spikes. I'm not sure if it's because the code is firing the GoToTarget() at a fast rate, but if that's the problem, does anyone know how I can fix it?
Gif: https://i.gyazo.com/0fa110b40bf219d3a60ed2fcffc6b043.gif
Code:
local Players = game:GetService("Players")
local RootPartNpc = script.Parent:WaitForChild("HumanoidRootPart")
local HumanoidNpc = script.Parent:WaitForChild("Humanoid")
local PathServ = game:GetService("PathfindingService")
--------------------------------------------------------------Locals
function GoToTarget(Vic)
local Path = PathServ:CreatePath()
Path:ComputeAsync(RootPartNpc.Position, Vic.Position)
local Waypoints = Path:GetWaypoints()
if Path.Status == Enum.PathStatus.Success then
for i, waypoint in ipairs(Waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
HumanoidNpc.Jump = true
end
HumanoidNpc:MoveTo(waypoint.Position)
local TmOut = HumanoidNpc.MoveToFinished:Wait(1)
if not TmOut then
HumanoidNpc.Jump = true
GoToTarget(Vic)
break
end
if (RootPartNpc.Position- Waypoints[1].Position).magnitude > 20 then
GoToTarget(Vic)
break
end
end
else
return false
end
end
function FIndPlayer()
for i, player in pairs(Players:GetPlayers()) do
local Character = player.Character or player.CharacterAdded:Wait()
local RootP = Character:WaitForChild("HumanoidRootPart")
local Dis = (RootPartNpc.Position-RootP.Position).magnitude
if Dis <= 700 then
return RootP
end
end
end
function Central()
local VictimGet = FIndPlayer()
if VictimGet then
GoToTarget(VictimGet)
end
end
--------------------------------------------------------------Functions
while wait(0.1) do
if HumanoidNpc.Health <= 0 then
break
end
Central()
end

2 comments
use RunService. This makes it that the code will run per frame, making it smooth and not choppy. Research about this if you don’t know what it is
Using RunService doesn't really change anything, plus if I were to use that, it would rapidly execute the threads, ultimately causing some issues.