Pathfinding script behaving weirdly

So, I have been working on a Piggy game, and said Piggy game has a bot. This bot has a pathfinding script located within it that basically just pathfinds to the nearest player constantly. However, I am facing 2 problems with this:

  1. For some reason, the bot will just get stuck on a wall, or a table, etc, and I will literally have to push it to get it unstuck.
  2. The bot seems to be unable to pathfind to the player in certain locations that it definitely should be able to. (Ex: A random spot on a completely flat part)
local PathfindingService = game:GetService("PathfindingService")

local path = PathfindingService:CreatePath({radius = 6.25, height = 5, canJump = true})

local humanoid = script.Parent.Humanoid

local destination

local waypoints

local stop

local waypointAmounts = {}

local playerToWaypoints = {}

local savedNumber = 1000000

local firstRun = true

local otherStop = false

--Find the closest player to the bot

function findNearestPlayer()
	
	for _, player in pairs(game.Players:GetChildren()) do
		path:ComputeAsync(script.Parent.HumanoidRootPart.Position, player.Character.HumanoidRootPart.Position)
		table.insert(waypointAmounts, #path:GetWaypoints())
		table.insert(playerToWaypoints, player)
	end
	
	for _, v in pairs(waypointAmounts) do
		if v ~= 0 then
			savedNumber = math.min(savedNumber, v)
		end
	end
	
	if playerToWaypoints[table.find(waypointAmounts, savedNumber)] ~= nil then
		return	playerToWaypoints[table.find(waypointAmounts, savedNumber)].Character	
	else
		return destination
	end
	
end

--Pathfind to the player

function move()
	for pos, waypoint in pairs(waypoints) do
		if pos ~= 1 then
			humanoid:MoveTo(waypoint.Position)
			wait()
			if stop then return false end
		end
	end
end

wait(15)

--Loop

while wait(0.03) do
	
	stop = true
	
	if firstRun then
		firstRun = false
		otherStop = false
	end
	
	repeat game:GetService("RunService").Stepped:Wait() until not otherStop
	
	stop = false
	
	destination = findNearestPlayer()
	
	waypointAmounts = {}
	
	playerToWaypoints = {}

	path:ComputeAsync(script.Parent.HumanoidRootPart.Position, destination.HumanoidRootPart.Position)

	waypoints = path:GetWaypoints()
	
	otherStop = move()
	
end

Anyone know why these things may be happening?

PathfindingService always had these flaws, just so your aware the ai won’t autojump in some situations so you’ll need to make it jump if it stays in the same position for a long time.

2 Likes

This fixed the problem, thanks!