Raycasts to Ignore Triggers
Just thought I’d share something kinda useful I learnt recently. I was working on this 3D First Person Shooter project as part of the GameDevHQ course, making use of raycasting for the weapon mechanics, when I found the rays were colliding with all colliders in the game (including those marked as isTrigger).
In most cases, we can just apply the ‘Ignore Raycast’ layer to the objects we want to ignore and that should do the trick:
But in this particular case, I had two colliders on the same GameObject: one for the actual collidable object, and the other to specify a radius around that object. I wanted raycast collisions to only work on the former, specifically so that blood spatters would appear on an enemy’s body in those positions, while I wanted the other to simply detect whether I was within range of an enemy’s attack. Since we can only tag objects rather than components in Unity, there didn’t seem to be much way of telling the raycast to ignore one of the colliders.
We could separate these two colliders, ensuring they’re placed on different GameObjects, but I found a quicker and easier solution which worked well for me and might work well for you:
1. Head over to Edit > Project Settings > Physics (or Physics 2D for 2D projects and colliders).
2. You should see a ‘Queries Hit Triggers’ option (as of Unity 2019.4.14f1). As the documentation explains, this boolean specifies whether ‘queries’ (raycasts, spherecasts, overlap tests, and the like) hit ‘Triggers’ by default. Unticking this should prevent your raycasts from colliding with any Colliders marked as ‘isTrigger’.
This is more of a ‘global’ solution however, affecting Physics across the entire project, but there could well be cases where you want raycasts to collide with specific isTrigger colliders but not others. In this case, you might want to look into the ‘QueryTriggerInteraction’ documentation for more tailored solution.
We can use the QueryTriggerInteraction enum when casting a ray, specifying the layer(mask) the ray interacts with and whether QueryTriggerInteraction is set to ‘Ignore’, ‘Collide’, or ‘UseGlobal’. In my case, I know that I never want the player’s bullets to collide with isTrigger colliders on the Default layer, so the following worked for me:
This particular code makes a raycast in the specified direction of the Ray variable, returns information within a RaycastHit struct, sends it over a distance of 50f/50 units, ensures it interacts with the LayerMask specified in the serialised variable (in my case, the Default layer), and ensures it passes through any Colliders marked ‘isTrigger’.
Hopefully one of these two solutions helps in your projects 😉