Ah, so we must be working backwards now…
local tool = script.Parent
local debris = game:GetService('Debris')
local function VisualizeRaycast(raycastResult: RaycastResult, originVector: Vector3)
local distance: number = (originVector - raycastResult.Position).Magnitude
local thickness: number = 0.1
local linearLine: Part = Instance.new("Part")
linearLine.Anchored = true
linearLine.CanCollide = false
linearLine.Size = Vector3.new(thickness, thickness, distance)
linearLine.CFrame = CFrame.lookAt(originVector, raycastResult.Position) * CFrame.new(0, 0, -(distance / 2))
linearLine.Color = Color3.fromRGB(math.random(0, 255), math.random(0, 255), math.random(0, 255))
linearLine.Parent = workspace
debris:AddItem(linearLine, 1)
return linearLine
end
script.Parent.Shoot.OnServerEvent:Connect(function(player, mousePosition)
local penetrationAttempts = tool:GetAttribute('Penetration')
local damage = tool:GetAttribute('Damage')
local Enemy = nil
local rOrigin = tool.Raycast.Position
local whitelist = {}
local blacklist = {player.Character}
while penetrationAttempts > 0 do
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = blacklist
local rayResult = game.Workspace:Raycast(rOrigin, (mousePosition - rOrigin) * 200, raycastParams)
if rayResult then
VisualizeRaycast(rayResult, rOrigin)
Enemy = rayResult.Instance.Parent
rOrigin = rayResult.Position
if Enemy:FindFirstChildOfClass('Humanoid') then
Enemy.Humanoid.Health -= damage
table.insert(whitelist, Enemy)
end
table.insert(blacklist, rayResult.Instance)
penetrationAttempts -= 1
else
break
end
end
end)
We are maintaining two separate tables, whitelist
and blacklist
, which keep track of the instances that we want to allow or disallow in subsequent raycasts. The whitelist
table initially contains only the player’s character, while the blacklist
table is empty.
In each iteration of the loop, we first create a new RaycastParams
object with a FilterType
of Blacklist
, and FilterDescendantsInstances
set to the blacklist
table. We then perform a raycast using these parameters.
If the raycast hits something, we add the instance to the blacklist
table (to prevent subsequent raycasts from hitting it), and if the instance is an enemy with a Humanoid
descendant, we reduce their health and add them to the whitelist
table.
We then decrement the penetrationAttempts
variable and continue with the loop, unless there are no more penetration attempts remaining, in which case we break out of the loop.
If this doesn’t work, there might be one more thing I can think of, but let me know!