so i have a pathfinding npc, which has smooth movement, until it doesnt. ive noticed that once it either fails to calculate a path or get stuck against a wall the movement just becomes jittery
here’s the code:
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = PathfindingService:CreatePath()
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function followPath()
for i, v in pairs(script.Parent:GetChildren()) do
if v:IsA("BasePart") then
v:SetNetworkOwner(nil)
end
end
-- Compute the path
local success, errorMessage = pcall(function()
path:ComputeAsync(character.PrimaryPart.Position, workspace:WaitForChild("Drixitty").HumanoidRootPart.Position)
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()
end
end)
-- Detect when movement to next waypoint is complete
if not reachedConnection then
reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached and nextWaypointIndex < #waypoints then
-- Increase waypoint index and move to next waypoint
nextWaypointIndex += 1
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
humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
humanoid.MoveToFinished:Wait()
else
warn("Path not computed!", errorMessage)
end
end
while true do
followPath()
game:GetService("RunService").Heartbeat:Wait()
end