Need help with Raycast gun!

Working on a raycast gun for my game.
I want the beam to stop once it hits a target, instead the beam goes miles past the target that it hit.

local function fireWeapon()
	if tool:GetAttribute("canFire") == true then
		tool:SetAttribute("canFire", false)
		
		local origin = firePart.Position
		
		local rand = (origin-mouse.Hit.p).magnitude/tool:GetAttribute("Accuracy")
		local randVect = Vector3.new(
			math.random((-rand)*10,(rand)*10)/10,
			math.random((-rand)*10,(rand)*10)/10,
			math.random((-rand)*10,(rand)*10)/10
		)

		local direction = (mouse.Hit.p - origin).Unit * tool:GetAttribute("Range")
		local result = workspace:Raycast(origin, (CFrame.new((origin+randVect),mouse.Hit.p).lookVector) * tool:GetAttribute("Range"))
		
		local intersection = result and result.Position or origin + direction
		local distance = (origin - intersection).magnitude

		local newBullet = Instance.new("Part")
		print(distance)
		newBullet.Size = Vector3.new(0.1, 0.1, distance)
		newBullet.CFrame = CFrame.new(origin, intersection)*CFrame.new(0, 0, -distance/2)
		newBullet.Anchored = true
		newBullet.Name = "Bullet"
		newBullet.BrickColor = BrickColor.new("Bright red")
		newBullet.CanCollide = false
		newBullet.Parent = game.Workspace.CurrentCamera

		script.Parent.Clicked:FireServer(mouse.Hit.p)
		game.Debris:AddItem(newBullet, 0.1)
		task.wait(tool:GetAttribute("FireRate"))
		tool:SetAttribute("canFire", true)
	end

end

Edit: The script works as expected, it damages the target you hit, but the beam goes through their character for a long distance.

All help and suggestions welcome!

If anyone could help me! That’d be great!

In order to help me, I would like you to show a video of the problem, and if possible, give a file of the item so I can find the error more easily.