Making a ray ignore a layer

I am trying to get a raycast to ignore a layer, but am having problems, I’m not entirely sure how to get layer 8 in this instance to be ignored.

    void ShootMissile()
    {
        LayerMask layerMask = ~1 << 8;
        RaycastHit hitInfo = new RaycastHit();
        bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo);
        if (hit)
        {
           //My amazing function
        }
    }

Am I declaring the layer mask correctly on Line 3?

On Line 5, where I think that I should add the LayerMask I don’t really want to add the condition of Max Distance. What do you suggest I do, add some arbitrary number into Max Distance? I did try the following -

LayerMask layerMask = ~1 << 8;
        RaycastHit hitInfo = new RaycastHit();
        bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 1000f, layerMask);

Which did not resolve my problem.

I’m happy to provide more information if needed, thanks.

1 Like

Its easy if you can expose the layer in the inspector.

public LayerMask Mask;

(...)

if (Physics.Raycast(startPoint, direction, out hit, maxDistance, Mask))
                {
                    // This is a hit.
                 }
else { // a miss }

Edit: also, here’s a static method I use to compare layers. I don’t recommend managing layers manually, using LayerMask is much more intuitive.

        public static bool LayerMatchTest(LayerMask approvedLayers, GameObject objInQuestion)
        {
            return ((1 << objInQuestion.layer) & approvedLayers) != 0;
        }
1 Like

Thanks @LaneFox , I have now changed my code to -
bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 50, Mask);

And have declared what the Mask is in the Inspector. Now when the ray is shot, it doesn’t go past if(hit) {}. Why isn’t it getting past the if statement any more? Regardless of where I am trying to hit (on the mask, or not), it isn’t hitting anything.

using UnityEngine;

public class RaycastMasking : MonoBehaviour {

    public LayerMask mask;
    public bool invertMask;
   
    void Update ()
    {
       LayerMask newMask = ~(invertMask ? ~mask.value : mask.value);

       RaycastHit hitInfo;
       bool hit = Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo, 50, newMask);
        if (hit) Debug.Log("Hit!");
    }
}

Make sure your layers are setup properly :slight_smile:

2 Likes

Thank you @LaneFox , that’s solved my problem. Everything is now working as intended :slight_smile:

1 Like