0
\$\begingroup\$

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.

enter image description here

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

enter image description here

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

In my case, using Physics2D.OverlapBoxAll fixed the issue

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .