Why does this linecast return false on the layer I specified?

I wrote some code to see if there’s a wall at a certain location:

if(Physics2D.Linecast(
        location,
        location, 
        LayerMask.NameToLayer("Blocks"), 
        -Mathf.Infinity, 
        Mathf.Infinity)
    ){
        return true;
    }

    return false;

    // A wall in the Blocks layer now returns false (should return true)
   // A wall in the Default layer returns true (should return false)

The weird thing is: though I specified to check the Blocks layer my method returns false when my walls are in the Blocks layer. However, when in the default layer it does hit my walls.

Why is my if returning false when my walls are in the Blocks layer and true if they are in the default layer?

2 Answers

2

Layermask.NameToLayer converts a name to a layer. Physics2D.Linecast takes a layermask. A layer is different from a layermask.

Change

LayerMask.NameToLayer("Blocks"), 

to

1<<LayerMask.NameToLayer("Blocks"), 

Yes. Unity 5 asks for all required permissions up front. If you want to do a flow seperately (show nice screens explaining why you are going to ask for certain permissions for example), you'd want to disable this and do it manually.

Isn’t the layerMask the layers to ignore? so if you do LayerMask.NameToLayer("Blocks") the LineCast will hit everything but the walls in the Blocks layer.

I don’t have much experience with layer masks but I think that is your problem…