I have a 2D game with several square objects (tiles) that each have a BoxCollider2D and a kinematic Rigidbody2D. I want to detect when one tile is located to the right of another tile, such as to prevent movement in that direction. All the tiles are on the default layer (layer 0). To detect if there is a tile to the right of the current tile, I use Physics.OverlapBox
, but for some reason, it never detecs any object (tile) in the OverlapBox, even though the visual gizmo in red which represents the OverlapBox clearly overlaps it.
This should trigger the line Debug.Log("intersected")
, as specified below, but it doesn't.
My code is as follows:
void Update()
{
rightSpacePosition = new Vector2(activeTile.transform.position.x + fBlockSize, activeTile.transform.position.y);
Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity);
if (intersectingBox.Length != 0)
{
Debug.Log("intersected")
}
}
I have also tried specifying the layer with
Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity, 0);
and
Collider[] intersectingBox = Physics.OverlapBox(rightSpacePosition, new Vector2(0.5f * fBlockSize, 0.5f * fBlockSize), Quaternion.identity, 1<<0);
In order to visually debug, I also draw a wirecube
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(rightSpacePosition, new Vector3(fBlockSize, fBlockSize));
}
Also, here are the settings of the Rigidbody2D and BoxCollider2D