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:
CodePudding user response:
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.
CodePudding user response:
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