So, I need help with updating a new path every second.
local RunService = game:GetService("RunService")
local PathfindingService = game:GetService("PathfindingService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local waypointsFolder = workspace:WaitForChild("Waypoints") --Red parts
local function randomWaypoint()
local waypoint = waypointsFolder:GetChildren()
local random = waypoint[math.random(1, #waypoint)]
return random
end
local function WalkTo(waypoint)
local pathParams = {
AgentHeight = character:GetExtentsSize().Y,
AgentRadius = character:GetExtentsSize().X,
AgentCanJump = false,
Costs = {
Danger = math.huge,
}
}
local path = PathfindingService:CreatePath(pathParams)
local success, errorMessage = pcall(function()
path:ComputeAsync(character.PrimaryPart.Position, waypoint.Position)
end)
if success and path.Status == Enum.PathStatus.Success then
for i,v in pairs(path:GetWaypoints()) do
repeat
humanoid:MoveTo(v.Position)
until humanoid.MoveToFinished:Wait()
randomWaypoint()
end
end
end
while task.wait(1) do
local random = randomWaypoint()
if random then
WalkTo(random)
end
end
1 Like
You’re gonna have to use path.Blocked to detect when the path is blocked.
local RunService = game:GetService("RunService")
local PathfindingService = game:GetService("PathfindingService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local waypointsFolder = workspace:WaitForChild("Waypoints")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function randomWaypoint()
local waypoint = waypointsFolder:GetChildren()
local random = waypoint[math.random(1, #waypoint)]
return random
end
local function followPath(destination)
local pathParams = {
AgentHeight = character:GetExtentsSize().Y,
AgentRadius = character:GetExtentsSize().X,
AgentCanJump = false,
Costs = {
Danger = math.huge,
}
}
local path = PathfindingService:CreatePath(pathParams)
local success, errorMessage = pcall(function()
path:ComputeAsync(character.PrimaryPart.Position, destination.Position)
end)
if success and path.Status == Enum.PathStatus.Success then
waypoints = path:GetWaypoints()
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
if blockedWaypointIndex >= nextWaypointIndex then
blockedConnection:Disconnect()
followPath(destination)
end
end)
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
nextWaypointIndex += 1
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
nextWaypointIndex = 2
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
end
end
while task.wait() do
local random = randomWaypoint()
if random then
followPath(random)
end
end
1 Like