- Home /
RaycastHit2D hits "itself"
I have gameobjects with circle colliders, and walls with box colliders. I make raycast to detect if there is something in front:
RaycastHit2D hit = Physics2D.Raycast(transform.position, currentNode.position);
However when I write the name of gameobject which raycast is hit, it shows me that it hit itself. Do I need to disable my Collider and then enable it after raycast? I know that there is masking, but I can't use it, because other gameobjects will raycast too to detect this gameobject. Any Ideas?
Answer by 767_2 · Nov 08, 2014 at 01:01 PM
you should put yourself on a layer ,make a new layer for example layer 8 and assign it to your object and then tell the raycast to do its job on all layers except your player layer, like below
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection (Vector3.forward), out hit, Mathf.Infinity, layerMask))
Answer by Tsilliev · Mar 19, 2018 at 12:29 PM
My solution was to turn off the collider before the raycast and turn it on at the end:
for (int i = 0; i < sectorCount; i++)
{
locations [i].GetComponent<CircleCollider2D>().enabled = false;
RaycastHit2D hit = Physics2D.Raycast (locations [i].transform.position, Vector2.up);
.
.
stuff
.
.
locations [i].GetComponent<CircleCollider2D>().enabled = true;
}