Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local PathfindingService = game:GetService("PathfindingService")
- local ready = true
- local NPC = script.Parent
- local humanoid = script.Parent.Humanoid
- local x = 0
- while true do
- wait()
- if ready == true then
- ready = false
- local blockedConnection
- local finishedConnection
- repeat
- wait()
- destination = game.Workspace.Points:GetChildren()[math.random(1,#game.Workspace.Points:GetChildren())]
- until(script.Parent.HumanoidRootPart.Position - destination.Position).magnitude > 17
- -- Create the path object
- local path = PathfindingService:CreatePath({
- AgentCanJump = false
- })
- -- Variables to store waypoints table and NPC's current waypoint
- local waypoints = {}
- local currentWaypointIndex = 1
- local function followPath(destinationObject)
- -- Compute and check the path
- path:ComputeAsync(NPC.HumanoidRootPart.Position, destinationObject.Position)
- -- Empty waypoints table after each new path computation
- waypoints = {}
- if path.Status == Enum.PathStatus.Success then
- -- Get the path waypoints and start NPC walking
- waypoints = path:GetWaypoints()
- -- Move to first waypoint
- currentWaypointIndex = 1
- humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
- else
- -- Error (path not found); stop humanoid
- humanoid:MoveTo(NPC.HumanoidRootPart.Position)
- end
- end
- local function onWaypointReached(reached)
- if reached and currentWaypointIndex < #waypoints then
- currentWaypointIndex = currentWaypointIndex + 1
- humanoid:MoveTo(waypoints[currentWaypointIndex].Position)
- --If NPC reaches destination
- if (script.Parent.HumanoidRootPart.Position - destination.Position).magnitude < 6 then
- ready = true
- finishedConnection:Disconnect()
- blockedConnection:Disconnect()
- end
- end
- end
- local function onPathBlocked(blockedWaypointIndex)
- -- Check if the obstacle is further down the path
- if blockedWaypointIndex > currentWaypointIndex then
- -- Call function to re-compute the path
- followPath(destination)
- end
- end
- followPath(destination)
- -- Connect 'Blocked' event to the 'onPathBlocked' function
- blockedConnection = path.Blocked:Connect(function(...)
- onPathBlocked(...)
- end)
- -- Connect 'MoveToFinished' event to the 'onWaypointReached' function
- finishedConnection = humanoid.MoveToFinished:Connect(function(...)
- onWaypointReached(...)
- end)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement