Reputation: 109
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?
Upvotes: 3
Views: 14817
Reputation: 254
To have your raycasts ignore all trigger colliders in 5.2 go to:
Edit > Project Settings > Physics > Uncheck "Queries Hit Triggers"
(If you're using an older version of Unity, the check box is called "Raycasts Hit Triggers")
Actually in version 5.2.0f3 it no longer says Raycasts... It now appears as: "Queries Hit Triggers" Uncheck if you want raycasts to pass through trigger colliders.
Upvotes: 7
Reputation: 125275
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.
Upvotes: 15
Reputation: 111
Change your triggered GameObjects layer on Ignore Raycast or use LayerMask https://docs.unity3d.com/ScriptReference/LayerMask.html
int targetLayer = 1 << LayerMask.NameToLayer("Target Layer");
public bool CheckVision(GameObject target)
{
RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange, targetLayer ));
if(ray.collider.name == target.name)
{
Debug.DrawRay(transform.position, target.transform.position - transform.position);
return true;
}
else
{
return false;
}
}
Upvotes: 1