Pathfinding NPC bugging out

Making an npc move around waypoint randomly and it works flawlessly, but sometime the npc just starts freezing for split seconds, and sometimes the npc moves perfectly

local PathfindingService = game:GetService("PathfindingService")
local PhysicsService = game:GetService("PhysicsService")

local dummy = script.Parent
local Humanoid = dummy:WaitForChild("Humanoid")

local waypointParts = game.Workspace.Waypoints:GetChildren()
local running = false

for i, v in pairs(dummy:GetDescendants()) do
	if v:IsA("Part") or v:IsA("BasePart") or v:IsA("MeshPart") then
		PhysicsService:SetPartCollisionGroup(v, "Player")
	end
end

local path = PathfindingService:CreatePath({
	AgentRadius = 3,
	AgentHeight = 6,
	AgentCanJump = false,
	WaypointSpacing = 0.5,
})

local waypoints = nil
local nextWaypointIndex = nil
local blockedConnection = nil
local reachedConnection = nil

local function followPath(destination)
	running = true
	
	local success, err = pcall(function()
		path:ComputeAsync(dummy.HumanoidRootPart.Position, destination)
	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()
					running = false
					print(running)
				end
			end)
		end
		
		nextWaypointIndex = 2
		Humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
	end
	
end

while wait(3) do
	if not running then
		local randomPickedPart = waypointParts[math.random(1, #waypointParts)]
		
		if randomPickedPart then
			
			waypoints = nil
			nextWaypointIndex = nil
			blockedConnection = nil
			reachedConnection = nil
			
			followPath(Vector3.new(math.random(1,5), 0, math.random(1,5)) + randomPickedPart.Position)
		end
	end
end

Btw for the collision groups Player x Player can’t collide

1 Like

You neeed to remember to VehicleSeat:SetNetworkOwner(nil) for so that the server handles all NPC physics and not default to the nearest player. I think you can do this just on the primarypart but I tend to do it on all npc parts

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.