Box-RayCast ignores layers

Hi, I have a small problem with Box-RayCasting.

Here would be my layer:

private int wallLayerMask = 1 << 6;

And this is the BoxCast:

RaycastHit2D hit = Physics2D.BoxCast(new Vector2(transform.position.x - 0.35f, transform.position.y - 0.25f), new Vector3(0.1f, 0.2f, 0.1f), 0, Vector2.left, wallLayerMask);

The Box-RayCast should only hit layers that correspond to the wallLayerMask (Ground). However, it still hits the player (default) and cannot find the error.

Does anyone have an idea what is wrong?

Thanks!

There’s nothing wrong with the query so something else is going wrong in your configuration.

I’d say pass the “wallLayerMask” using a public LayerMask field in your script and configure it in the inspector rather than hardcoding it like that.

Whatever GameObjects comprise your “player” that contain 2D colliders, make sure they are all on a specific layer and selct that layer in your script.

Note that if you already have a Collider you can simply use: Unity - Scripting API: Collider2D.Cast

I don’t understand it either, everything seems to be correct. If I change it to normal RayCasting and no longer use BoxCast, it works.

It’s because you are passing the layer mask in the distance place (you can check the API for BoxCast). In order to fix your problem, you should do this:

RaycastHit2D hit = Physics2D.BoxCast(new Vector2(transform.position.x - 0.35f, transform.position.y - 0.25f), new Vector3(0.1f, 0.2f, 0.1f), 0, Vector2.left, distance, wallLayerMask);

Replace distance with your desired value in the code above.