How do I incorporate PathFindingService into my existing script?

I’m making a module script for a system for a guard that patrols 2 points, and if they see a player they will chase and attack them

This works perfectly fine, however the guard gets stuck behind simple corners without the use of PathFindingService.

I’ve looked into ways to try and tackle this issue, but the best I’ve gotten is really blocky pathfinding, that sometimes works, and is very choppy with movements.

Here is the main part of my script currently:

function module.Guard(guard)
	local pointA = guard:FindFirstChild("PointA")
	local pointB = guard:FindFirstChild("PointB")
	
	if not pointA or not pointB then return end
	
	local humanoid = guard.Humanoid
	local hrp = guard.HumanoidRootPart
	
	local chasing = false
	
	while wait() do
		local closestPlayer = FindClosestPlayer(guard.HumanoidRootPart)
	
		if chasing == false then
			task.wait(math.random(1,2))
			humanoid:MoveTo(pointA.Position)
			
			repeat wait()
				local ray = castVisionRay(guard, 35, 20, 20) -- just my way of detecting if the player is in its vision (guard, angle, castamount, range), this returns the ray it fires if the ray detects a player
				
				if ray and ray.Instance and game.Players:GetPlayerFromCharacter(ray.Instance.Parent) then
					chasing = true
					humanoid:MoveTo(ray.Instance.Parent.HumanoidRootPart.Position)
					break
				else
					chasing = false
				end
				
			until (hrp.Position - Vector3.new(pointA.Position.X, hrp.Position.Y, pointA.Position.Z) ).magnitude <= 1
			
			if chasing == false then
				task.wait(math.random(1,2))
				humanoid:MoveTo(pointB.Position)
			end			
			
			repeat wait()
				local ray = castVisionRay(guard, 35, 20, 20)
				
				if ray and ray.Instance and game.Players:GetPlayerFromCharacter(ray.Instance.Parent) then
					chasing = true
					humanoid:MoveTo(ray.Instance.Parent.HumanoidRootPart.Position)
					break
				else
					chasing = false
				end
				
			until (hrp.Position - Vector3.new(pointB.Position.X, hrp.Position.Y, pointB.Position.Z) ).magnitude <= 1

		end
		
		if chasing == true then
			humanoid:MoveTo(ray.Instance.Parent.HumanoidRootPart.Position) -- the place where I want it to path find, as this is where they are chasing the player
			if debounce == false then
				coroutine.wrap(damageRig)(guard, closestPlayer.Character, 10, 1)
			end
		end
	end
end

If you are struggling to analyse my messy code, the part at the bottom where it checks if the guard is chasing is where I am planning to have the guard pathfind.

Any help is appreciated, and I’m not sure if the solution includes replacing the Humanoid:MoveTo() with a different function or not, which is another thing I’m confused on. Many Thanks.

1 Like

You could probably use AgentParams, specifically AgentRadius to address your issue with pathfinding