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

[...ANSWERED?] Returning a list of everything intersecting a ray using WorldRoot:Raycast?

I want to get a table of EVERYTHING that intersects a ray using WorldRoot:Raycast. Is there an alternative function to accomplish this, or do I just have to recursively perform new raycasts with a blacklist that contains all instances previously intersecting the ray?

2 comments

0

A ray can only hit one part.

0

Well a ray is a line and a line can intersect multiple parts

1 answer

Great question dude. Unfortunately it doesn't look like there's an existing function that returns all results intersecting a ray. Here's how you can implement the recursive method in a function:


local RaycastUtils = {}

function RaycastUtils.RaycastAll(origin, direction)	--Returns a list of RaycastResults on a ray
	
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	local blacklist = {}
	
	local result = workspace:Raycast(origin, direction, raycastParams)
	local results = {result}
	
	while result do
		
		blacklist[#blacklist + 1] = result.Instance
		raycastParams.FilterDescendantsInstances = blacklist	--Weirdly the FilterDescendantsInstances property doesn't store a reference to the table assigned, it clones it instead. So the table has to be reassigned whenever a new instance is added to the blacklist.
		result = workspace:Raycast(origin, direction, raycastParams)
		results[#results + 1] = result
		
	end
	
	return results
	
end

return RaycastUtils

This implementation lacks some functionality, such as passing your own whitelist/blacklist, but that's not really necessary for your use case.

Additionally, since the blacklist filters by descendants instead of just the instances in the array, any intersecting descendants of a previous raycast result will be missed. You can either design around that in your game or write a new function to account for that. Once again, the former option is suited to your use case.

P.S. There may also be some optimizations available by changing the origin of each raycast to the position of the last result and decreasing the ray's distance to compensate, but i'm not really in the mood to explore that right now.

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