- Home /
Physics.Raycast not checking layermask properly?
I'm having issues with a Physics.Raycast call in some buggy code that I inherited for a project I'm on, where agents trying to Raycast to a "LatchPoint" layer, which is user layer 8.
Here is the code with the variable names made easier to read:
RaycastHit hitInfo;
int myMask = 1 << 8;
if (Physics.Raycast(sourceTransform.position, (raycastTarget - sourceTransform.position).normalized, out hitInfo, Mathf.Infinity, myMask))
{
storedTransform = hitInfo.transform;
Debug.Log(storedTransform.name);
}
The Debug.Log will print the name of a CharacterController in the "Default" layer, and not get to the CapsuleCollider inside of it on the "LatchPoint" layer. Am I using my mask incorrectly?
Your code seems good. I have a Linecast written the exact same and it only hits the stuff in the masked layer. I have done this with Raycasts and the mask worked correctly there as well. This also reflects the layer masking example correctly http://unity3d.com/support/documentation/Components/Layers.html. All I can suggest is to recheck your scene. Ensure that the CharacterController being hit is actually on the Default layer and that the CapsuleCollider's transform is named differently. Do you maybe have another CharacterController with that name on layer 8? Try turning off layers to check.
Also, make sure that no other debug logs are sending the message since this one will not fire if nothing was hit. Try something like changing your Debug to read something like Debug.Log(String.Format("Raycast Hit (0) on layer (1)", storedTransform.name, storedTransform.gameObject.layer));
Answer by JonManatee · Aug 09, 2010 at 06:05 PM
This is what fixed it, although I'm not entirely sure why:
RaycastHit hitInfo;
int myMask = 1 << 8;
if (Physics.Raycast(sourceTransform.position, (raycastTarget - sourceTransform.position).normalized, out hitInfo, Mathf.Infinity, myMask))
{
storedTransform = hitInfo.collider.gameObject.transform;
Debug.Log(storedTransform.name);
}
i am surprised that this bug is still there.. just got the same issue.
Your answer
Follow this Question
Related Questions
Raycast 2D with origin inside the collider 1 Answer
Colliders Not Doing Their Job 2 Answers
RaycastAll related question 1 Answer
Collision position - Improving on the 'grounded' mechanic 2 Answers