Hey there, I’m currently making a simple pathfinding, it works perfectly when the target isn’t changing its position, but will shutter / halt itself if the target does change. Here’s my code:
local PathFinding = {}
PathFinding.__index = PathFinding
local PathFindingService = game:GetService("PathfindingService")
local defaultAgentParams = {
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
}
function PathFinding.init(AI, target)
local self = setmetatable({}, PathFinding)
self.Path = PathFindingService:CreatePath(defaultAgentParams)
self.AI = AI
self.AIHrp = AI.HumanoidRootPart
self.TargetHRP = target
self.posChangeInterval = 0.5
self.oldTargetPos = self.TargetHRP.Position
self.Finished = false
self.pathComputed = false
return self
end
local function checkPosDiff(oldPos, newPos, interval)
local n = (oldPos - newPos).Magnitude
return n >= interval
end
function PathFinding:ComputePath()
local t = tick()
self.Path:ComputeAsync(self.AIHrp.Position, self.TargetHRP.Position)
--print("Time took to generate path: " .. tostring(tick() - t))
--[[self.timesComputed += 1]]
if self.Path.Status == Enum.PathStatus.Success then
local waypoints = self.Path:getWaypoints()
for i, point in pairs(waypoints) do
local targetPos = self.TargetHRP.Position
if not self then break end
if checkPosDiff(self.oldTargetPos, targetPos, self.posChangeInterval) then
-- Recompute the path if the target has moved
self.oldTargetPos = targetPos
self:ComputePath()
print("Broke loop")
break
end
local part = Instance.new("Part")
part.Size = Vector3.new(0.5, 0.5, 0.5)
part.Anchored = true
part.CanCollide = false
part.Position = point.Position
part.Parent = workspace
--print("Begin Moving")
self.AI.Humanoid:MoveTo(point.Position)
self.AI.Humanoid.MoveToFinished:Wait()
--print("Finished Moving")
self.oldTargetPos = targetPos
part:Destroy()
end
--self.Finished = true
end
end
function PathFinding:DestroyPath()
for i, _ in pairs(self) do
self[i] = nil
end
self = nil
setmetatable(self, nil)
end
return PathFinding
The AI will compute a new path if the target has moved, this check is done in the for loop for the movement itself (Note that the script is not wrapped in a while loop and it should not be)
If the target is constantly moving, the AI will stop itself to compute a new path and detect the movement again, repeats the process (Which in turn cause the AI to stop), instead of following the target. Video example: https://gyazo.com/90416b5fb738f48f1c9900adc6273247
I want the AI to CONSTANTLY follow the plr, no matter what. I tried adding a i > 2
in the movement check but the shuttering is still immense.
Any help is appreciated profusely!