Physics2D.OverlapBox detecting objects out of range.

Hi everyone!

I’m working on a wall slide system for my character and I’m using an OverlapBox to detect walls. This is made by using Bounds as parameter to size and position, as following:

     private Transform rightBound;
    [SerializeField] private Bounds frontSensor;

    public bool FrontWallSensor()
    {
        return Physics2D.OverlapBox(rightBound.position, frontSensor.size, 0, groundLayer);
    }

8547176--1142555--Example5.PNG

private void OnDrawGizmos()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireCube(rightBound.position + frontSensor.center, frontSensor.size);
    }

The problem is that when the character jumps and hits the ceiling, FrontWallSensor() returns true, even with that offset between the character’s collider and the OverlapBox (yellow). Am I debugging it wrong? Or is OverlapBox that imprecise?

Whilst so many posts on these forum states a problem as the physics engine not working somehow, there’s nothing wrong with that query so it’ll be what you’re doing here.

I obviously cannot debug this for you but to be honest, there’s a far easier/faster/better way to do this than using all this manual bounds/offset stuff. Simply use the existing contacts that the physics engine produces and query them.

You can use a ContactFilter2D in any query to ask that you only get collision normal angles within a specific range and on specific layers etc. You can retrieve the contacts using GetContacts or even simpler, use the IsTouching call on the Rigidbody2D or the specific collider.

The IsTouching can be used for things such as checking if you’re currently grounded or, as you want, if you’re touching a wall. A basic example of this can be seen in this video which also links to my PhysicsExamples repo. It’s only allowing jumping if the slope is withbin a certain angle:

Hope this helps.

The problem was a silly math mistake, should have casted the box, the same way I debugged:

     public bool FrontWallSensor()
    {
        return Physics2D.OverlapBox(rightBound.position + frontSensor.center, frontSensor.size, 0, groundLayer);
    }