Raycasts with CanCollide checking

It’s kinda lame that Roblox doesn’t include a built-in way for raycasts to ignore BaseParts with CanCollide set to false. This module fixes that. While I was at it, I modified the syntax to be easier on the eyes.

Using the module:

Raycast = require(game.ReplicatedStorage.RaycastsWithCanCollideChecking)

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {}
raycastParams.IgnoreWater = true

RaycastResult = Raycast({
					Params = raycastParams,
					Origin = Vector3.new(0,0,0),
					ToPoint = Vector3.new(0,5,0), -- Direction = Vector3.new(0,5,0),
					CheckCanCollide = false -- true by default
				})

I’ve also added a convenient ToPoint feature. If you’re raycasting to find a part between two points, and you don’t want to bother thinking about it, you can simply include a “ToPoint” parameter. If you want to use a LookVector instead, you can use the “Direction” parameter. If you use both, ToPoint overrides Direction.

Direction:
image

ToPoint:

The main mechanics are less than 50ish lines of code, but thinking about the recursion is just another layer of complexity that you might want to avoid if you’re making something already complicated.

13 Likes

Or you can just do a pcall on getting the descendants of Workspace to add them to the FilterDescendants table to avoid recursion.

1 Like

I’m pretty sure that concept would be really laggy; You’re going after every descendant of workspace every raycast.

You only need to add them to the FilterDescendants list in your RaycastParams once. Then you can even go a step further and to .DescendantAdded to add to the FilterDescendants if it is also non-cancollide. Where can the lag possibly come from if you are only running this once + adding an event?

I see, I misunderstood what you meant by the ‘getting the descendants of Workspace’ part.

Another possible problem with that solution is that Parts can have CanCollide re-enabled. Which will still be ignored by Raycast.

I might actually change this module to do that instead. The current method of raycasting where the CanCollide==false part hits seems to have funky behavior when MeshParts are involved.

I’ve went ahead and updated the module to do it that way. The old method seems to have issues with MeshParts. Here’s the old version incase someone wanted it: oldRaycastsWithCanCollideChecking - Roblox