How can I do a raycast but limit the ray to Line of Sight?
Do you mean just raycasting a normal ray ? like this…
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
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;
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.