Npc walking off path

I have created a npc that walkes to random checkpoints, but the npc would kinda go off path and I want to make him not able to walk in certain places

When he walks from point A to point B he walks throught the red boxes but I want him to walk on the path and stay away from the red boxes, walk like the green line and not the blue.

Is there a way I could do that? any help will be appreciated

Script
local Npc = script.Parent
local humanoid = Npc.Humanoid

local PathFindingService = game:GetService("PathfindingService")
local function getPath(destination)
	local pathparams = {
		["AgentHight"] = 6,
		["AgentRadius"] = 4,
		["AgentCanJump"] = true
	}
	local path = PathFindingService:CreatePath(pathparams)
	path:ComputeAsync(Npc.HumanoidRootPart.Position, destination.Position)
	return path
end

local function walkTo(destination)
	local path = getPath(destination)

	for index, waypoint in pairs(path:GetWaypoints()) do
		humanoid:MoveTo(waypoint.Position)
		humanoid.MoveToFinished:Wait()
	end
end


local function patrol()
	local waypoints = workspace.Waypoints2:GetChildren()
	local randomNum = math.random(1, #waypoints)
	walkTo(waypoints[randomNum])
end

while wait(0.5) do
	patrol()
end

The pathfinding will take the shortest path, try to put a hole at the place his walking, the pathfiding should go in the right direction

1 Like

Put a Costs key-pairs to bias it to go to the path
Character Pathfinding

1 Like