Gun hit detection not working

Server:

-- Main Variables --
local debris = game:GetService("Debris")
local event = script.Parent:WaitForChild("FireEvent")
local gun = script.Parent
local handle = script.Parent.Handle


-- Configuration --
local BulletSpeed = 500
local BulletDMG = 5

-- Function --
event.OnServerEvent:Connect(function(player, pos)
	print("Input received, engaging check..")
	if player.Character:FindFirstChild(gun.Name) then -- check if gun equipped
		local char = player.Character
		-- Projectile --
		print("Check successful!")
		local bullet = Instance.new("Part")
		bullet.Parent = game.Workspace
		bullet.BrickColor = BrickColor.new("Bright yellow")
		bullet.Material = Enum.Material.Neon
		bullet.Size = Vector3.new(0.795, 0.59, 2.235)
		bullet.Position = handle.Position
		bullet.CanCollide = false
		bullet.CFrame = CFrame.lookAt(bullet.Position, pos)
		print("Bullet is created.")

		-- Movement --
		local BodyVelocity = Instance.new("BodyVelocity")
		BodyVelocity.Parent = bullet
		BodyVelocity.Velocity = bullet.CFrame.LookVector * BulletSpeed
		BodyVelocity.P = BulletSpeed
		print("Bullet is moving.")

		-- Bullet Lifetime --
		debris:AddItem(bullet, 5)

		-- Hit Detection --
		local connection
		connection = bullet.Touched:Connect(function(hit)
			if hit.Parent:FindFirstChild("Humanoid") then
				print("Player hit!")
				hit.Parent.Humanoid.Health -= BulletDMG
			elseif hit:IsA("Part") then
				if not hit.Parent:FindFirstChild("Humanoid") then
					bullet:Destroy()
				end
			end
		end)


	else
		print("Check unsuccessful.")
		player:Kick("Check failed, security measures engaged.")
		print(player.Name .. " has been kicked.")
	end
end)

The issue is that it prints all messages, but the bullets don’t fire - probably because they’re getting destroyed as soon as fired since it collides with the player wielding it, and it’s been ravaging my mind because I’m just annoyed.
image

1 Like

ye the bullet prob touches its own gun and gets destroyed you might want to move the bullet that is getting instanced out of the gun like a little bit further so it isnt touching i had this issue to with a gun

In the Touched event, check if the bullet touched the gun model and make sure that doesn’t destroy the bullet.

if hit.Parent == bullet.Parent then
--do nothing
end

If you’re still struggling I recommend you use FastCast. It’s a open source projectile system which is easy to set up and has many useful features and optimisations.

1 Like

I fixed it, thank you. (characters)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.