Hello developers, So I was working on my AI that uses parts and has pathfinding, but when player moves for some time it gets stuck and just stays on place this is code :
local ps = game:GetService("PathfindingService")
local ts = game:GetService("TweenService")
local path = ps:CreatePath({
AgentHeight = 4;
AgentRadius = 4;
AgentCanJump = false;
})
local currentWaypointPos = Vector3.new(0,0,0)
local currentMovePosition = Vector3.new(0,0,0)
local target = nil
local blockedConnection = nil
local targetConnection = nil
local targetConnectionDebounce = false
local moveTween = nil
function getVictim()
local curVictim = nil
local curDist = math.huge
for _,i in pairs(game.Players:GetPlayers()) do
if i and i.Character then
local dist = (i.Character.HumanoidRootPart.Position - script.Parent.Position).Magnitude
if dist < curDist then
curDist = dist
curVictim = i.Character
end
end
end
return curVictim
end
function move(pos)
if targetConnection ~= nil then
targetConnection:Disconnect()
targetConnection = nil
end
path:ComputeAsync(script.Parent.Position, pos)
currentMovePosition = pos
if path.Status == Enum.PathStatus.Success then
if target ~= nil then
targetConnection = target.Humanoid:GetPropertyChangedSignal("MoveDirection"):Connect(function()
return move(target.HumanoidRootPart.Position)
end)
end
for _,i in pairs(path:GetWaypoints()) do
task.spawn(function()
repeat task.wait()
break
until targetConnection == nil
end)
currentWaypointPos = i.Position
local dist = (script.Parent.Position - i.Position).Magnitude
moveTween = ts:Create(script.Parent, TweenInfo.new(script.Parent:GetAttribute("Speed"),Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0), {
Position = i.Position + Vector3.new(0,3,0);
})
moveTween:Play()
moveTween.Completed:Wait()
end
moveTween = nil
if blockedConnection ~= nil then
blockedConnection:Disconnect()
blockedConnection = nil
end
if targetConnection ~= nil then
targetConnection:Disconnect()
targetConnection = nil
end
end
end
task.spawn(function()
while task.wait() do
target = getVictim()
if target ~= nil then
move(target.HumanoidRootPart.Position)
end
end
end)
--Make debounce for target connection so it doesnt loop
task.spawn(function()
while targetConnectionDebounce == true do
task.wait(0.3)
targetConnectionDebounce = false
end
end)
task.spawn(function()
while task.wait() do
if currentWaypointPos ~= nil then
local dist = (script.Parent.Position - currentWaypointPos).Magnitude
if dist > 3 then
script.Parent.CFrame = script.Parent.CFrame:Lerp(CFrame.lookAt(script.Parent.Position, currentWaypointPos + Vector3.new(0,3,0)), 0.3)
end
end
end
end)
Is there solution?