How can i make my ray dont go through parts? Like bullets in real life?

Good morning guys, i have a question,when i was testing my gun i could see that, firing my gun to a part, i could see the ray just going through. How can i make this like the ray dont go through a part? is Collision Groups my answer? or i am missing something of RaycastParams()? thanks in advance, hope you have a great day!
here is my code btw

local shootEvent = game.ReplicatedStorage:WaitForChild("Shoot")
local tool = script.Parent
local shootsound = tool.ShootSound
local CurrentAmmo = tool.CurrentAmmo
local BulletsFolder = game.Workspace.balas
local debris = game:GetService("Debris")
local DAMAGE = 30
local HEADSHOT_DAMAGE = 70



local function bulletsTrajectory(origin, direction)
	local midpoint = origin + direction / 2 
	local part = Instance.new("Part")
	part.Anchored = true
	part.CanCollide = false
	part.Material = Enum.Material.Neon
	part.BrickColor = BrickColor.new("Cool yellow")
	part.CFrame = CFrame.new(midpoint, origin)
	part.Size = Vector3.new(0.1,0.1,direction.magnitude)
	part.Parent = BulletsFolder
	debris:AddItem(part, 0.2)
end


shootEvent.OnServerEvent:Connect(function(player, originPos, destinationPos)
	local directionRay = (destinationPos - originPos).Unit * 100
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {tool}
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local ResultOfRaycasting = workspace:Raycast(originPos, directionRay, raycastParams)
	if ResultOfRaycasting then
		local hitpart = ResultOfRaycasting.Instance 
		if hitpart and hitpart.Parent.Name ~= tool.Parent.Parent.Name then
			hitpart.Parent:FindFirstChild("Humanoid"):TakeDamage(20)
			end
			if hitpart.Name == 'Head' and hitpart.Parent:FindFirstChild("Humanoid") then
			hitpart.Parent:FindFirstChild("Humanoid"):TakeDamage(70)
			end
	end
	bulletsTrajectory(originPos, directionRay)
end)
1 Like

There are two ways you can do this:

  1. Whitelisting - Parts to collide with (not recommended)
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Whitelist
params.FilterDescendantsInstances = {
   // parts to collide with
   game.Workspace.Player1,
   game.Workspace.Wall1,
   game.Workspace.Wall2,
   game.Workspace.Wall3,
}
  1. Blacklisting - Parts to not collide with (recommended)
local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Blacklist
params.FilterDescendantsInstances = {
   // parts to NOT collide with
   game.Workspace.PlayerWithTheGun, // to avoid shooting themselves
   game.Workspace.InvisibleCeiling
}

Specifying a model will make the ray not collide with its descendants too, so you could blacklist all invisible walls for example if they are in a single model.

4 Likes

thanks man, i was confused, thanks!!!

1 Like