Why is my gun shooting itself?

I’m working on a gun, and when I shoot the gun in first person, it shoots the barrel part. When I take the barrel part away, it shoots the handle. What would be ideal would be if I could make the gun bypass all of the parts in the gun model or anything I don’t want it to shoot.

-- Variables
 
local UserInputService = game:GetService("UserInputService")

local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()
local tool = script.Parent
local shoot = script.Parent.AKM.shootPart

local equipped = false

-- Raycasting Function

local function semiFire()
	local camera = workspace.CurrentCamera
	
	local semiParams = RaycastParams.new()
	semiParams.FilterDescendantsInstances = {} 
	semiParams.FilterType = Enum.RaycastFilterType.Blacklist
	
	local function semiResult(x, y)
	    local unitRay = camera:ScreenPointToRay(mouse.x, mouse.y)
	    return workspace:Raycast(unitRay.Origin, unitRay.Direction * 500, semiParams)
	end
	
	local semiResultV = semiResult(mouse)
	if semiResultV then
		local hitPart = semiResultV.Instance
		local newCF = CFrame.new(shoot.Position, hitPart.Position)
		
		local rayResult = workspace:Raycast(shoot.Position, newCF.LookVector * 500)
		print(rayResult)
		
		local hit = rayResult.Instance
		
		local beam = Instance.new("Part", workspace)
		beam.BrickColor = BrickColor.new("Really red")
		beam.FormFactor = "Custom"
		beam.Material = "Neon"
		beam.Transparency = 0.5
		beam.Anchored = true
		beam.Locked = true
		beam.CanCollide = false
		
		local distance = (shoot.CFrame.p - hit.CFrame.p).magnitude
		
		beam.Size = Vector3.new(0.1, 0.1, distance)
		beam.CFrame = CFrame.new(shoot.CFrame.p, hit.CFrame.p) * CFrame.new(0, 0, -distance / 2)
		
		game:GetService("Debris"):AddItem(beam, 0.1)
		
		local humanoid = hit.Parent:FindFirstChild("Humanoid")
		if not humanoid then
			local humanoid = hit.Parent.Parent:FindFirstChild("Humanoid")
		end
		if not humanoid then end
		if humanoid then 
		
			local semiEvent = game:GetService("ReplicatedStorage").Guns.AKM:WaitForChild("semiEvent")
			semiEvent:FireServer(humanoid, hit)
		end	
	end
end
-- Equip / Unequip

tool.Equipped:Connect(function(mouse)
	equipped = true
end)

tool.Unequipped:Connect(function(mouse)
	equipped = false
end)

-- Firing


UserInputService.InputBegan:Connect(function(input)
	if equipped == true then
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			semiFire()
		end
	end
end)


UserInputService.InputEnded:Connect(function(input)
	if equipped == true then
		if input.UserInputType == Enum.UserInputType.MouseButton1 then
			
		end
	end
end)

Thanks!

You need to add an ignore list to the raycast. (aka the plr character and/or gun)

You use workspace:FindPartOnRayWithIgnoreList(rayObject, {table ignore list (player.Character)} )

this should solve your problem

Edit: also PS, try to use the position of the raycast as it will always return instead of a part which sometimes wont return (aka no part was hit).

1 Like