Pathfinding stutter premium edition

this is a little script for a companion dude that follows you around. he keeps distance from you a bit so he’ll stop when he’s too near and start playing an idle anim. at first, i used a simple MoveTo function which goes really smoothly and i made him pathfind when you were already 45 studs away. however, that combo kinda makes him get stuck, so i decided to solely use pathfinding.

the pathfinding tho is a bit janky. he pathfinds to you a bit, and when he stops when he’s near you, he stays in that state for a while even if you’ve backed up from him a bit before he pathfinds again.

local me = script.Parent
local animer = me.Animator
local anim = me.idle
local track = animer:LoadAnimation(anim)
local debounce = false

-- simply finds the nearest player
local function findNearestPlayer()
	local nearestPlayer = nil
	local shortestDistance = math.huge

	for _, player in pairs(game.Players:GetPlayers()) do
		if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
			local distance = (player.Character.HumanoidRootPart.Position - me.Parent.HumanoidRootPart.Position).magnitude
			if distance < shortestDistance then
				shortestDistance = distance
				nearestPlayer = player
			end
		end
	end

	return nearestPlayer
end

local PathfindingService = game:GetService("PathfindingService")
local destination = nil
-- computes a lil path for npc to go
function createPath(destination)
	local path = PathfindingService:CreatePath({
		AgentRadius = 4,
		AgentHeight = 5,
		AgentCanJump = false,
		AgentJumpHeight = 7,
		AgentMaxSlope = 45,
		WaypointSpacing = 3
	})
	path:ComputeAsync(me.Parent.HumanoidRootPart.Position, destination)
	return path
end
-- initiates pathfinding
function go(destination)
	local path = createPath(destination)
	local waypoints = path:GetWaypoints()
	for _, waypoint in pairs(waypoints) do
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			me:ChangeState(Enum.HumanoidStateType.Jumping)
		end
		me:MoveTo(waypoint.Position)
		me.MoveToFinished:Wait()
	end
end




while task.wait(1) do
	local plr = findNearestPlayer()
	local hrp = plr.Character.HumanoidRootPart
	go(hrp.Position)
	local distance = (me.Parent.HumanoidRootPart.Position - hrp.Position).Magnitude
	if distance > 5 then
		track:Stop()
		me.WalkSpeed = 7
	else
		if track.IsPlaying == false then
			track:Play()
		end
		me.WalkSpeed = 0
	end
end

i have no idea if it’s the script or roblox’s pathfinding system itself.