Hi, I’ve been working on an npc, but it looks like it’s walking a bit weirdly like if it was sometimes being blocked by something despite nothing being on the way. Why is that?
robloxapp-20230313-1803429.wmv (2.6 MB)
Here’s the script:
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local path = PathfindingService:CreatePath()
local char = script.Parent
local humanoid = char:WaitForChild("Humanoid")
local waypoints
local nextWaypointIndex
local reachedConnection
local blockedConnection
local function followPath(destination)
-- Compute the path
local success, errorMessage = pcall(function()
path:ComputeAsync(char.PrimaryPart.Position, destination)
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(destination)
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)
else
warn("Path not computed!", errorMessage)
end
end
while task.wait(math.random(3,8)) do
local randomX = char.Torso.Position.X + math.random(-85,85)
if math.abs(randomX) < 28 then
randomX *= 5
end
local randomZ = char.Torso.Position.Z + math.random(-85,85)
if math.abs(randomZ) < 28 then
randomZ *= 5
end
local TEST_DESTINATION = Vector3.new(randomX, char.Torso.Position.Y, randomZ)
followPath(TEST_DESTINATION)
end```