Prevent players from shooting themselves

I’ve made a paintball gun that when activated, fires a RemoteEvent. Upon the RemoteEvent being fired, it spawns a bullet. If the bullet hits a humanoid, it takes damage. Else, it gets removed.

The issue here is that you can shoot yourself using the gun, as seen in the video below:

Code

Client:

local plr = game:GetService("Players").LocalPlayer
local shootEvent = game.ReplicatedStorage.ShootEvent
local tool = script.Parent
local handle = tool:FindFirstChild("Handle")

script.Parent.Equipped:Connect(function(mouse)
	mouse.Button1Down:Connect(function()
		local head = workspace[plr.Name].Head.CFrame.LookVector
		local mousep = CFrame.new(workspace[plr.Name].Head.Position, mouse.Hit.p).lookVector
		local diff = head - mousep
		local ray = Ray.new(script.Parent.Handle.CFrame.p, (plr:GetMouse().Hit.p - script.Parent.Handle.CFrame.p).unit * 300)
		local part, pos = workspace:FindPartOnRay(ray, plr.Character, false)
		
		shootEvent:FireServer(handle, mouse.Hit)
	end)
end)

Server:

local function getBullet()
	local p = Instance.new("Part")
	p.Parent = workspace
	p.Size = Vector3.new(.5, .1, .5)
	p.BrickColor = BrickColor.Random()
	p.CanCollide = false
	p.Shape = Enum.PartType.Ball
	Instance.new("BodyVelocity", p)
	return p
end

game.ReplicatedStorage.ShootEvent.OnServerEvent:Connect(function(player, handle, mousePos)
	local bullet = getBullet()
	bullet.CFrame = handle.CFrame * CFrame.new(0, 0, -1.5)
	bullet.CFrame = CFrame.new(bullet.Position, mousePos.p)
	bullet.BodyVelocity.Velocity = bullet.CFrame.LookVector * 120
	
	bullet.Touched:Connect(function(hit)
	local Humanoid = hit.Parent:FindFirstChild("Humanoid")
	
	if Humanoid then
		Humanoid:TakeDamage(10)
		bullet:Destroy()
	end
	end)
	
	game.Debris:AddItem(bullet, 1)
end)
2 Likes
if Humanoid and not Humanoid:IsDescendantOf(player.Character) then
8 Likes

I think vNotSiren, it’s not really a good efficient method, you can just do, FindPartOnRayWithIgnoreList

workspace:FindPartOnRayWithIgnoreList(Ray, {Player.Character})

That’d work if he wasn’t using .Touched to deal damage.

3 Likes