unity3d – Using layerMasks with Physic2D.Linecast() in Unity C#

unity3d – Using layerMasks with Physic2D.Linecast() in Unity C#

Your problem is on this line:

RaycastHit2D hitWall = Physics2D.Linecast (start, end, 8);

It should be as follows:

RaycastHit2D hitWall = Physics2D.Linecast (start, end, (1<<8));

Why? Because that argument wants a layer mask, ie a bit mask for the layer, not an index.

That argument doesnt want just one layer, it gives the option for casting against multiple layers as defined by order of the bits in the mask (all bits will be 0 except for the one you made 1). This allows you to combine masks, and do things like ~(1<<8) which casts against all layers except 8.

Relevant documentation: https://docs.unity3d.com/Manual/Layers.html

Edit:

An additional problem is that RaycastHit2D is a struct type. That means it will always be not null.

You want to check if (hitWall.collider == null) {

See: http://answers.unity3d.com/questions/691622/why-does-raycast2d-always-return-non-null.html

unity3d – Using layerMasks with Physic2D.Linecast() in Unity C#

Leave a Reply

Your email address will not be published.