Need help updating path without choppy movement

I am making a entity that detects players and chases them but the problem is the script that updates player path uses break and it has to play the function again which makes a choppy movement

I’ve tried seeing other forums but they are different than mine, mine has a wander script, they don’t.

I’ve only pasted the important part

function attack(target)
	local path = getPath(target.HumanoidRootPart)
	local distance = (monster.HumanoidRootPart.Position - target.HumanoidRootPart.Position).Magnitude	

	if distance > 3 then
		local waypoints = path:GetWaypoints()
		for index, waypoint in pairs(waypoints) do
			humanoid:MoveTo(waypoint.Position)
			humanoid.MoveToFinished:Wait()
			if (waypoints[#waypoints].Position - target.HumanoidRootPart.Position).Magnitude > 5 then
				-- recalculate path
				
				print ("Player moved, Recalculating path")
				break
			end
		end
	else

		monster.Head.JumpScare:Play()
		
		local playerDeath = game.ReplicatedStorage.Events:WaitForChild("playerDeath")
		local player = game.Players:GetPlayerFromCharacter(target)
		playerDeath:FireClient(player, monster)
		
		local attackAnim = humanoid:LoadAnimation(script.Attack)
		attackAnim:Play()
		attackAnim.Stopped:Wait()
		target.Humanoid.Health = 0
	end
end

function walkTo(goal)
	local path = getPath(goal)
	
	if path.Status == Enum.PathStatus.Success then
	for index, waypoint in pairs(path:GetWaypoints()) do
		local target = findTarget()
			if target and target.Humanoid.Health > 0 then
			attack(target)
			break
		else
			humanoid:MoveTo(waypoint.Position)
			humanoid.MoveToFinished:Wait()
		end
		end
	else
		humanoid:MoveTo(goal.Position - (monster.HumanoidRootPart.CFrame.LookVector * 10))
	end
end

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

while wait(0.2) do
	patrol()
end
1 Like