Raycast hitting layer explicitly told to ignore (and doesn't even have collider!)
Hey friends,
I have a raycast emanating from an enemy towards my player. The code calling the raycast is as follows and is called in the enemy's script:
void FireZeMissile(){
Debug.Log("BOOM");
int layerMask = (1 << 10) | (1 << 12) | (1 << 23);
layerMask = ~layerMask;
RaycastHit hit;
Ray shootRay = new Ray(transform.position, player.transform.position - transform.position);
if (Physics.Raycast(shootRay, out hit, 1000f, layerMask, QueryTriggerInteraction.Collide)){
if (hit.transform.gameObject.tag == "Shield"){
player.gameObject.GetComponent<PlayerHandler>().shieldscript.TakeDamage(damage);
Debug.Log("Shield hit.");
}
Debug.Log(hit.transform.gameObject.name + ", layer: " + hit.transform.gameObject.layer;
Debug.DrawLine(shootRay.origin, hit.point, Color.red, 100f);
}
}
My "BOOM" debug message gets hit of course and the shield debug never gets hit. Incredibly, the last Debug.Log reads "FPSController, layer: 23". How is this possible?? Didn't I just tell it NOT to hit layer 23 when I set up my layermask? Why could this be happening?? Additionally, "FPSController" does NOT have a collider. It has a child that does but that child is layered as "Player" (layer 11).
Does anyone know what is happening here?
Facing the same problem and apparently no one was able to find a solution xD
Answer by hexagonius · Dec 03, 2016 at 11:26 AM
This is called compound collider. I assume, you have a Rigidbody on your FPSController. a rigidbody combines alle colliders under it into one big collider referencing itself when any collision is detected. So the child CAN be hit due to layer 11, but the collider belongs to your FPSController, which is why your log is logging what it logs (??? ;) )
In more detail, the raycast hits the exact collider it should, no nonsense, using the layer for that exact individual collider, and raycasthit.collider tells you that.
But then raycasthit.transform is really a helper function. It climbs the tree to a compound collider parent (the first rigidbody it sees, I think.) It's never been documented that I know of.