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 =

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

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

		game.Debris:AddItem(newBullet, 0.1)
		tool:SetAttribute("canFire", true)


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.