Auto Switch Between High and Low Arc Based on Target Distance is not working

i have been trying to improve my Predicted Projectile Angle but i have a problem that i don’t know how to fix.

i want the turret to Switch between high arc and low/flat
something like this:

But the script doesn’t work the way it’s supposed to.
the script:

local part = script.Parent
local target = workspace.target
local projectileSpeed = 3000 
local gravity = workspace.Gravity
local switchDistance = 300

function GetLaunchAngle(origin, targetPos, speed, gravity, useHighArc)
	local displacement = targetPos - origin
	local horizontal = Vector3.new(displacement.X, 0, displacement.Z).Magnitude
	local vertical = displacement.Y
	local speedSquared = speed ^ 2

	local discriminant = speedSquared^2 - gravity * (gravity * horizontal^2 + 2 * vertical * speedSquared)
	if discriminant < 0 then
		return nil
	end

	local root = math.sqrt(discriminant)
	local angleLow = math.atan((speedSquared - root) / (gravity * horizontal))
	local angleHigh = math.atan((speedSquared + root) / (gravity * horizontal))

	return useHighArc and angleHigh or angleLow
end

while true do
	task.wait(0.1)

	local origin = part.Position
	local targetPos = target.Position
	local toTarget = targetPos - origin
	local horizontal = Vector3.new(toTarget.X, 0, toTarget.Z)
	local distance = horizontal.Magnitude

	local useHighArc = distance < switchDistance
	local angle = GetLaunchAngle(origin, targetPos, projectileSpeed, gravity, useHighArc)

	if angle then
		--(left/right)
		local yaw = math.atan2(-horizontal.X, -horizontal.Z)

		-- Construct rotation
		local rotation = CFrame.Angles(0, yaw, 0) * CFrame.Angles(angle, 0, 0)
		part.CFrame = CFrame.new(origin) * rotation
		print(useHighArc and "HIGH arc" or "LOW arc")
	else
		warn("out of range")
	end
end