--pathfinding function, a single use function that allows for easy pathfind settup
function pathFind(destination, agent)
local path = pathfindService:CreatePath({
AgentRadius = .75,
AgentHeight = 2,
AgentCanJump = false,
AgentCanClimb = false,
WayPointSpacing = 1,
Costs = {Water = 20, ExceptionArea = math.huge}
})
--setting up variables for later
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
--follow the path to the given destination
local function followPath(givenDestination)
print("called")
local success, errorMessage = pcall(function()
path:ComputeAsync(agent.PrimaryPart.Position, givenDestination)
end)
if success and path.Status == Enum.PathStatus.Success then
-- Get the path waypoints
waypoints = path:GetWaypoints()
-- Detect if path becomes blocked
blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
-- Check if the obstacle is further down the path
if blockedWaypointIndex >= nextWaypointIndex then
-- Stop detecting path blockage until path is re-computed
blockedConnection:Disconnect()
-- Call function to re-compute new path
followPath(givenDestination)
end
end)
-- Detect when movement to next waypoint is complete
if not reachedConnection then
reachedConnection = agent.Humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
-- Increase waypoint index and move to next waypoint
nextWaypointIndex += 1
agent.Humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
reachedConnection:Disconnect()
blockedConnection:Disconnect()
end
end)
end
-- Initially move to second waypoint (first waypoint is path start; skip it)
nextWaypointIndex = 2
agent.Humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
else
warn("Path not computed!", errorMessage)
end
end
followPath(destination)
end
Essentially just a retrofitted version of the Roblox pathfinding script found on the API reference. It is made to work with an NPC.
How then am I able to cancel movement, or override it? For example, an NPC is moving somewhere and someone talks to them while they’re moving, and I’d want them to stop or something. How can I do this?