- Home /
Don't allow raycasts to go through colliders?
How can I do a raycast but limit the ray to Line of Sight?
Answer by Tehnique · Aug 26, 2014 at 09:04 AM
Raycasts don't go through colliders by design, that is their purpose, to detect the first collider the ray intersects. If your raycasts go through colliders, there might be a problem with your setup (maybe you ignore some layers by passing a layer mask to the ray, or you have "IsTrigger" enabled on the colliders).
You can also specify the range for the raycst, if that helps in any way, look at the "distance" parameter when creating a ray.
Answer by AngryBurritoCoder · Aug 26, 2014 at 09:05 AM
Do you mean just raycasting a normal ray ? like this...
Physics.Raycast(Raycast_Start_Position,Raycast_Direction,Distance);
EDIT: If you included layerMask in your ray function, this can cause trouble, since masks allow for rays to go through colliders ( the ones you choose or all if in default)
and maybe a stupid thing to say, but make sure your objects have colliders too xD
Yeah, I forgot to mention that the raycasts all use layer masks! I want a raycast on layermask 1 to stop and return false if it hits a collider on layer 2 before hitting anything on layer 1. Is there an actual way to do this and keep the layermask, or should I do a normal raycast then check hit.collider.gameobject and see if it's on that layer, or what's the best way to handle it?
EDIT: and the colliders that I want to stop it are disabled although the GameObject holding it is active. can i leave them disabled or do I have to keep them enabled?
easiest way to use layermask and raycast ( personally i find this extremely easy) is to make the Layermask public. public Layer$$anonymous$$ask layersToCheck;
What that gives you is an option in the editor to choose which layers you dont want to ignore, then apply that layersToCheck to the raycast and it will work.
so if you want to ignore wall but hit floor, you would check the floor option in the editor window and it will only hit the floor colliders
Answer by kacyesp · Aug 26, 2014 at 06:32 PM
You must provide the layer you want to hit as the layer mask argument. You must also make sure the colliders you wish to hit are enabled.
Now, given your requirement of "return false if it hits a collider on layer 2 before hitting anything on layer 1" with no other assumptions, what I would do is something like:
RaycastHit2D rayHit1 = Physics.Raycast( rayOrigin, rayDirection, rayDistance, layer1 );
RaycastHit2D rayHit2 = Physics.Raycast( rayOrigin, rayDirection, rayDistance, layer2 );
if ( rayHit1 && rayHit2 )
if ( rayHit2.distance < rayHit1.distance )
return false;