Hello devs, So I’m making AI for part but I need to make it check if player moved away so NPC doesn’t go to last spot where player was, I have tried implementing this but it doesn’t seem doing anything, my 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 target = 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)
path:ComputeAsync(script.Parent.Position, pos)
if path.Status == Enum.PathStatus.Success then
for _,i in pairs(path:GetWaypoints()) do
currentWaypointPos = i.Position
local dist = (script.Parent.Position - i.Position).Magnitude
local moveTween = ts:Create(script.Parent, TweenInfo.new(0.5,Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, 0, false, 0), {
Position = i.Position + Vector3.new(0,3,0);
})
moveTween:Play()
moveTween.Completed:Wait()
moveTween:Destroy()
end
end
end
task.spawn(function()
while task.wait() do
target = getVictim()
if target ~= nil then
move(target.HumanoidRootPart.Position)
end
end
end)
task.spawn(function()
while task.wait() do
if target ~= nil then
target.HumanoidRootPart:GetPropertyChangedSignal("Position"):Connect(function()
move(target.HumanoidRootPart.Position)
return move(target.HumanoidRootPart.Position)
end)
end
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)