I have a function that checks if a game object can see another game object without anything blocking its view:
public bool CheckVision(GameObject target)
{
RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
if(ray.collider.name == target.name)
{
Debug.DrawRay(transform.position, target.transform.position - transform.position);
return true;
}
else
{
return false;
}
}
The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?
Layer mask operation is not required for this. You don't have to use layers if this is only to ignore Colliders marked as triggers. This operation is now built in with Unity 5.2 and above.
1.For 3D, pass QueryTriggerInteraction.Ignore to the Physics.Raycast function.
int layer = 1 << LayerMask.NameToLayer("Default");
Physics.Raycast(cameraRay, out hit, distance, layer, QueryTriggerInteraction.Ignore);
2.For 2D, set Physics2D.queriesHitTriggers to false if you don't want it to detect triggers. Set it to true when you want it to detect triggers once again. Make sure to set it before calling the Physics2D.Raycast function.
Don't detect triggers:
Physics2D.queriesHitTriggers = false;
Detect triggers:
Physics2D.queriesHitTriggers = true;
Your are looking for the 2D version.
Note:
I have seen reports of this not working on some certain version of Unity which is a bug but I assume it is now fixed. If not then use layers as described by l1sten.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With