Pathfinding stuck on walls

I have made a npc follow you with the pathfindingservice but you can still get him stuck on walls.

Code :


local Npc = script.Parent
local HumanoidRoot = Npc.HumanoidRootPart
local Humanoid = Npc.Humanoid
HumanoidRoot:SetNetworkOwner(nil)

function CreatePath(Destination)
	local Path = PathfindingService:CreatePath({
		AgentRadius = 5.268;
		AgentHeight = 7;
	})
	
	Path:ComputeAsync(HumanoidRoot.Position, Destination.Position)
	
	return Path
end

function FindPlayer()
	local Players = game:GetService('Players'):GetPlayers()
	local MaxDistance = math.huge
	local NearestTarget
	
	for _, Target in pairs(Players) do
		if Target.Character then
			if Target.Character.Humanoid.Health <= 0 then
				return
			end
			
			local NewTarget = Target.Character
			local Distance = (HumanoidRoot.Position - NewTarget.HumanoidRootPart.Position).Magnitude
			
			if Distance < MaxDistance then
				NearestTarget = NewTarget
			end
		end
	end
	
	return NearestTarget
end

function WalkTo(Destination)
	local NewPath = CreatePath(Destination)
	
	for _, waypoint in pairs(NewPath:GetWaypoints()) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			Humanoid.Jump = true
		end
		
		Humanoid:MoveTo(waypoint.Position)
	end
end

function AttackTarget(Target)
	if Target.Humanoid.Health <= 0 then
		return
	end
		
	WalkTo(Target.HumanoidRootPart)
end

while task.wait() do
	local Target = FindPlayer()
	if Target then
		AttackTarget(Target)
	end
end

the script doesn’t check if the path is wrong, also you should add Humanoid.MoveToFinished:Wait() after Humanoid:MoveTo(waypoint.Position) so the npc waits until he reaches the point hes walking to before moving on to the next one

function WalkTo(Destination)
	local NewPath = CreatePath(Destination)

	for _, waypoint in pairs(NewPath:GetWaypoints()) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			Humanoid.Jump = true
		end

		Humanoid:MoveTo(waypoint.Position)
		local TimeOut = Humanoid.MoveToFinished:Wait(1)
		if not TimeOut then
			if Humanoid.Health > 0 then -- prevent it from trying to retry the path after dying
				warn("Stuck, retrying path.")
				WalkTo(Destination)
			end
			break
		end
	end
end

Should work. Let me know if it doesnt, it’s about almost 5 AM and I didn’t test this. Also, you generally shouldn’t use while task.wait() do. Heartbeat would be a better alternative.

EDIT: Wrong reply, sorry lol