What's wrong with my AI? (Random PathFinding)

I’m trying to create an AI that will allow the NPC to follow a randomly generated path avoiding obstacles along the way but the NPC randomly gets stuck and walks around with a jerky motion. Any tips on how I can improve this?


(Jerky walking motion is easier to see at 0:24 - 0:28)

AI Script:

local human = script.Parent:WaitForChild("NPC")
local torso = script.Parent:WaitForChild("UpperTorso")
local Distance = 50
local Distance2 = -50
local StandTime = 0.1
local clone = script.Parent:Clone()

function move()
	local randX = math.random(Distance2,Distance)
	local randZ = math.random(Distance2,Distance)
	local goal = torso.Position + Vector3.new(randX,0,randZ)

	local path = game:GetService("PathfindingService"):CreatePath()
	path:ComputeAsync(torso.Position, goal)
	local waypoints = path:GetWaypoints()
	
	if path.Status == Enum.PathStatus.Success then
		for _, waypoint in pairs(waypoints) do
			if waypoint.Action == Enum.PathWaypointAction.Jump then
				human.Jump = true
			end
			human:MoveTo(waypoint.Position)
			human.MoveToFinished:Wait(2)
		end
	else
		wait(.1)
	end
end

human.Died:Connect(function()
	wait(1)
	clone.Parent = workspace
	game:GetService("Debris"):AddItem(script.Parent,0.1)
end)

while wait(StandTime) do
	move() 
end

Roblox’s PathfindingService is not very good when it comes to terrain (changes in the z axis). That’s why you see the AI getting stuck when it goes into the bush. There are things you can do to reduce this happening, like minimizing the distance that is traveled each time.

If you want to make your AI feel more natural, you can consider using a node-based PathFinding system. I don’t have much knowledge on the matter, but this link should send you in the right direction: Node Mapper for Pathfinding

I hope this helped!

2 Likes