'Unity Physics2D.BoxCast() can not find GameObject on specific layer
I have a huge problem with the BoxCast method in Unity. I'm trying to get information if there is any GameObject under the player that is on a specific layer but there is a problem. The method can not find any GameObject that is under the player even when there clearly is an object.
private CapsuleCollider2D PlayersCapsuleCollider;
private bool CanJump()
{
RaycastHit2D ray = Physics2D.BoxCast(PlayersCapsuleCollider.bounds.center, PlayersCapsuleCollider.bounds.size, 0f, Vector2.down, Mathf.Infinity, 12 /*number of the layer mask*/);
return ray.collider != null;
}
(Maybe useful information) But this only looks like this when I'm trying to find an object on layer 12, if I'm looking for an object on different layer (layer number 3) the BoxCast is finding the player's collider (Player is on Default layer 0)
More - I hope - useful screens:
The layer of the platform that the player is standing on:
Solution 1:[1]
Physics queries like BoxCast are looking for a LayerMask rather than the int representing the layer's ID number. To get the LayerMask for layer ID 12 you would shift the 12th bit to 1 with 1 << 12
. There is an easier way to create a LayerMask though, you can use either the method provided in the other answer, or you can create a serialized LayerMask field on your class and simply assign the layers in the inspector.
Solution 2:[2]
you should get the layer mask with:
LayerMask layerMask = LayerMask.GetMask("Floor");
and pass that into Physics2D.BoxCast
instead of 12
you can read more about layer masks at https://docs.unity3d.com/ScriptReference/LayerMask.html
Solution 3:[3]
I had a similar issue with Physics2D.Boxcast() but I was able to solve it somehow. First correct the layer issue as kobi-c suggested, then I think the next problem is coming from the ray distance set to Math.Infinity
. The box is extending to infinity so it will always collide even if it's in the air. Try setting a small distance like 0.1f
. So that when it's in the air it will not collide unless it's at that small distance. I hope this helps
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Boxfriend |
Solution 2 | Kobi-c |
Solution 3 |