Bullet Tracer Issue

My bullet tracer for my gun will not shoot in the sky, i tried to make it so it can like this:

	local endPosition = origin + direction * 300
	if result then
		endPosition = result.Position
	end

But it still isnt working. When i shoot the ground or any part the bullet tracer appears. Please help me fix this issue, here is my script

local rs = game:GetService("ReplicatedStorage")
local remote = rs:WaitForChild("GunFire")
local reloadRemote = rs:WaitForChild("ReloadEvent")
local debris = game:GetService("Debris")

remote.OnServerEvent:Connect(function(plr, barrel, mousePosition, sound)
	local origin = barrel.Position
	local direction = (mousePosition - origin).Unit
	local result = workspace:Raycast(origin, direction * 300)
	local particles = barrel:GetChildren()
	
	for _, particle in pairs(particles) do
		if particle:IsA("ParticleEmitter") then
			particle.Enabled = true
		end
	end

	local newSound = Instance.new("Sound")
	newSound.SoundId = sound
	newSound.Parent = barrel
	newSound:Play()
	debris:AddItem(newSound, newSound.TimeLength + 1)
	
	local attachmentStart = Instance.new("Attachment", barrel)
	attachmentStart.Position = Vector3.new(0, 0, 0)

	local endPosition = origin + direction * 300
	if result then
		endPosition = result.Position
	end

	local attachmentEnd = Instance.new("Attachment", workspace.Terrain)
	attachmentEnd.Position = endPosition

	local beam = Instance.new("Beam")
	beam.Attachment0 = attachmentStart
	beam.Attachment1 = attachmentEnd
	beam.Texture = "rbxassetid://5889875399"
	beam.Width0 = 0.5
	beam.Width1 = 0.9
	beam.TextureMode = Enum.TextureMode.Stretch
	beam.TextureSpeed = 1
	beam.LightEmission = 1
	beam.LightInfluence = 1
	beam.Segments = 10
	beam.Color = ColorSequence.new(Color3.fromRGB(255, 134, 93))
	beam.Parent = barrel

	task.delay(0.1, function()
		beam:Destroy()
		attachmentStart:Destroy()
		attachmentEnd:Destroy()
		for _, particle in pairs(particles) do
			if particle:IsA("ParticleEmitter") then
				particle.Enabled = false
			end
		end
	end)

	if result then
		print("Ray hit: ", result.Instance.Name)
	end
end)

reloadRemote.OnServerEvent:Connect(function(plr, barrel, sound)
	print(barrel, sound)
	local newSound = Instance.new("Sound")
	newSound.SoundId = sound
	newSound.Parent = barrel
	newSound:Play()
	debris:AddItem(newSound, newSound.TimeLength + 1)
end)