Am making NPC that following moving item
if items’s position is changed
create new path for it
But NPC is following old path first,
How can I delete old path?
local PathfindingService = game:GetService("PathfindingService")
local Dummy = game.Workspace.Dummy
local humanoid = Dummy.Humanoid
local destination = game.Workspace.eeee
local pos = destination.Position
local path = PathfindingService:CreatePath()
path:ComputeAsync(Dummy.HumanoidRootPart.Position, pos)
local waypoints = path:GetWaypoints()
while true do
if pos ~= destination.Position then
pos = destination.Position
print("target moved")
local path = PathfindingService:CreatePath() ---Make new path
path:ComputeAsync(Dummy.HumanoidRootPart.Position, pos)
local waypoint = path:GetWaypoints()
end
for _, waypoints in pairs(waypoints) do
local part = Instance.new("Part")
if waypoints.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
humanoid:MoveTo(waypoints.Position)
humanoid.MoveToFinished:Wait()
end
end
At each step in for _ waypoints, I check to see if the Target has moved and break the for loop if it has. This forces the while true loop to recalculate the path.
Move the waypoint navigation out of the while true loop and place it into a separate function. Call this function after path has been computed:
local function waypointMove() -- Added function for waypoint navigation
for _, waypoints in pairs(waypoints) do
-- Recalulate Target Position here. If moved then break
if pos ~= destination.Position then
return
end
end
local part = Instance.new("Part")
if waypoints.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
humanoid:MoveTo(waypoints.Position)
humanoid.MoveToFinished:Wait()
end
end
while true do
if pos ~= destination.Position then
pos = destination.Position
print("target moved")
local path = PathfindingService:CreatePath() ---Make new path
path:ComputeAsync(Dummy.HumanoidRootPart.Position, pos)
waypoints = path:GetWaypoints()
end
-- Call waypointMove function
waypointMove()
end