Gun spread issue | v2

My first problem was halfway solved here, but also not quite solved.

My code (the next section wont make sense without the code above):

local player = game.Players.LocalPlayer
local tool = script.Parent
local config = script.Parent.config
tool.Equipped:connect(function(mouse)
	print("Tool equipped!")
 
	mouse.Button1Down:connect(function()
		print("Mouse pressed!")
		local endPos = mouse.Hit.p
		local startPos = player.Character.Head.CFrame.p
		
		local CF = CFrame.new(startPos,endPos)*CFrame.Angles(math.rad(math.random(-0,0)),math.rad(math.random(-0,0)),0)
		
		local DirVec = CF.LookVector
		local ray = Ray.new(tool.Handle.CFrame.p, DirVec.unit * config.range.Value)
		local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)
 
		local beam = Instance.new("Part", workspace)
		beam.BrickColor = BrickColor.new("Bright red")
		beam.FormFactor = "Custom"
		beam.Material = "Neon"
		beam.Transparency = 0.25
		beam.Anchored = true
		beam.Locked = true
		beam.CanCollide = false
 
		local distance = (tool.Handle.CFrame.p - position).magnitude
		beam.Size = Vector3.new(0.3, 0.3, distance)
		beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
 
		game:GetService("Debris"):AddItem(beam, 0.1)
 
		if part then
			local humanoid = part.Parent:FindFirstChild("Humanoid")
 
			if not humanoid then
				humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
			end
 
			if humanoid then
				humanoid:TakeDamage(30)
			end
		end
		print(distance)
	end)
end)

Basically I want to make a gun with… spread, obviously. The problem is with literally 0 “spread” (line 12) it still has the littlest bit of spread. Please and thank you :))

It’s possible that the ray you’re casting is hitting the beam, causing your shots to deviate slightly. Try adding the beams to the ray cast’s ignore list. You’ll need to use CollectionService:AddTag and FindPartOnRayWithIgnoreList.


Right after creating the beam, do

game:GetService("CollectionService"):AddTag(beam, "Beam")

And replace your raycast with:

local ignoreList = game:GetService("CollectionService"):GetTagged("Beam")
if player.Character then
    table.insert(ignoreList, player.Character)
end
local part, position = workspace:FindPartOnRayWithIgnoreList(ray, ignoreList, false, true)
1 Like

Nope, this is just a little project as I cant concentrate on one thing for the life of me.

The spread is coming from your player head,due to animations.

Set your startPos to be based off your character’s primary part or the gun’s handle.

2 Likes