Hello fellow devs! So I’ve been working on Pathfinding module for my horror game’s AI, but it seems to be choppy/laggy/jittery and I don’t really know how to fix it, here’s footage :
And there’s the code :
local workspace = game:GetService("Workspace") --because of my anti-exploit
local module = {}
local ps = game:GetService("PathfindingService")
module.__index = module
function module.new(rig : Model,params)
if not rig then return end
local self = setmetatable({},module)
self.rig = rig
repeat task.wait() until self.rig:FindFirstChildWhichIsA("Humanoid")
self.hum = self.rig:FindFirstChildWhichIsA("Humanoid")
self.hrp = self.rig:WaitForChild("HumanoidRootPart")
self.wps = nil
self.curWaypoint = 1
self.lastTime = os.time()
if params then
self.Path = ps:CreatePath(params)
else
self.Path = ps:CreatePath()
end
coroutine.wrap(function()
while task.wait() do
local diff = os.time() - self.lastTime
if diff > self.hum.WalkSpeed * 0.8 then
local sucess,err = pcall(function()
if self.Path and self.curWaypoint and self.wps then
if self.curWaypoint < #self.wps then
self.curWaypoint += 1
else
self.curWaypoint = 1
end
end
end)
if not sucess then
warn(err)
self.curWaypoint = 3
end
self.lastTime = os.time()
end
end
end)()
return self
end
function module:Run(position : Vector3)
if self.rig then
for _,i in pairs(self.rig:GetDescendants()) do
if i:IsA("BasePart") then
pcall(function()
i:SetNetworkOwner(nil)
end)
end
end
end
pcall(function()
if not position then return end
if not self.Path or not self.hrp then return end
self.Path:ComputeAsync(self.hrp.Position,position)
if self.Path.Status == Enum.PathStatus.Success then
self.wps = self.Path:GetWaypoints()
if self.wps[self.curWaypoint] then
if self.wps[self.curWaypoint].Action == Enum.PathWaypointAction.Jump then
self.hum.Jump = true
end
self.hum:MoveTo(self.wps[self.curWaypoint].Position)
end
else
self.hum:MoveTo(position)
end
end)
end
return module