Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I get this recurring raycasting method to actually work?

So I'm trying a new method of raycasting for my gun engine stuff. The idea is that when you shoot, if the ray hits something that's either already in the ignoreList or that is invisible and/or cancollide false, then it'll continuously recast until it finally hits an object that is visible and/or solid. Now, what's going on is if I shoot at the part that is solid and visible, it'll print the part's name no problem. However, if it hits nothing, or hits an object that is invisible or cancollide false, then it gives me an error. Here's the code:

local player = game.Players.LocalPlayer
local char = player.Character
local mouse = player:GetMouse()
local cam = workspace.CurrentCamera
local tool = script.Parent

local equipped = false
local shooting = false

local ignoreList = {}


local function CastRay(fromPoint, vector, ignoreList)
	local vector = vector - fromPoint
	local ray = Ray.new(fromPoint, vector.Unit * vector.Magnitude)
	return workspace:FindPartOnRayWithIgnoreList(ray, ignoreList or {}, false, true)
end

-- Casts and recasts until it hits either: nothing, or something not transparent or collidable
local function PiercingCast(fromPoint, vector, ignoreList) --NOTE: Modifies ignoreList!
	repeat
		local hitPart, hitPoint = CastRay(fromPoint, vector, ignoreList)
		if hitPart and (hitPart.Transparency > 0.95 or hitPart.CanCollide == false) then
			table.insert(ignoreList, hitPart)
		else
		return hitPart, hitPoint
		end
	until false
end



tool.Equipped:connect(function()
	if not equipped then
		equipped = true
	end
end)


mouse.Button1Down:connect(function()
	if not shooting then
	--	local hitPart, hitPoint = CastRay(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 500)
		--if hitPart and hitPart.Transparency == 1 or hitPart.CanCollide == false then
			local hitPart, hitPoint = PiercingCast(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 50000)
		if hitPart then			
			print(hitPart.Name)	
		end
	--	end
	end
end)

NOTE: This is in a local script

Here's the error:

Players.Player1.Backpack.Tool.LocalScript:24: bad argument #1 to 'insert' (table expected, got nil)

1 answer

✓ Accepted answer

It's casting an error because, you excluded the ignoreList parameter when calling the function.

local hitPart, hitPoint = PiercingCast(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 50000, ignoreList)

Even if you already have the variable on line 10, it's going to use the parameter.

This discussion is preserved as it was. New answers, comments, and votes are closed.