i want to make the Character follow the player with pathfinding, the problem is that at some point the character go back and return to his road,.
this causes him to make him (and mostly me) unable to progress and even fall
local rig = script.Parent
local zhum = rig:WaitForChild("zHumanoid")
local pathfinding = game:GetService("PathfindingService") --creates the pathfinding settings
local waypoints = {}
local waypointIndex = 1
local path = pathfinding:CreatePath({
AgentRadius = 2,
AgentHeight = 5,
AgentCanJump = true,
AgentCanClimb = true
})
local function DetectClosestPlayer ()
--get the player
local closestPlayer = nil
local closestDistance = nil
for i, player in pairs(game.Players:GetPlayers()) do
--get the distance between the player and the npc
local distance = (player.Character.HumanoidRootPart.Position - rig.HumanoidRootPart.Position).Magnitude
--check closest pl
if closestDistance == nil or distance < closestDistance then
closestDistance = distance
closestPlayer = player
end
end
return closestPlayer
end
local function createPath ()
local player = DetectClosestPlayer()
if player then
waypoints = nil
--get the path to the player
path:ComputeAsync(rig.HumanoidRootPart.Position, player.Character.HumanoidRootPart.Position)
waypoints = nil
waypoints = path:GetWaypoints()
waypointIndex = 1
waypointIndex += 1
local part = Instance.new("Part")
part.Parent = workspace
part.Size = Vector3.new(1,1,1)
part.Position = waypoints[waypointIndex].Position
part.Anchored = true
part.CanCollide = false
part.Material = Enum.Material.Neon
end
end
local function move ()
zhum:MoveTo(waypoints[waypointIndex].Position)
end
zhum.MoveToFinished:Connect(function()
waypointIndex += 1
if waypoints[waypointIndex].Action == Enum.PathWaypointAction.Jump then
zhum.Jump = true
end
move()
end)
task.wait(5)
while task.wait(1) do
DetectClosestPlayer()
if DetectClosestPlayer() then
createPath()
move()
end
end
i think the problem is the loop at the end of the script but idk how to change that