Search Unity

Resolved Physics2D.OverlapBox detecting objects out of range.

Discussion in 'Physics' started by Phoenix248, Oct 28, 2022.

  1. Phoenix248

    Phoenix248

    Joined:
    Sep 20, 2019
    Posts:
    52
    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:

    Code (CSharp):
    1.      private Transform rightBound;
    2.     [SerializeField] private Bounds frontSensor;
    3.  
    4.     public bool FrontWallSensor()
    5.     {
    6.         return Physics2D.OverlapBox(rightBound.position, frontSensor.size, 0, groundLayer);
    7.     }
    Example5.PNG
    Code (CSharp):
    1. private void OnDrawGizmos()
    2.     {
    3.         Gizmos.color = Color.yellow;
    4.         Gizmos.DrawWireCube(rightBound.position + frontSensor.center, frontSensor.size);
    5.     }
    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?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,500
    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.
     
  3. Phoenix248

    Phoenix248

    Joined:
    Sep 20, 2019
    Posts:
    52
    The problem was a silly math mistake, should have casted the box, the same way I debugged:

    Code (CSharp):
    1.      public bool FrontWallSensor()
    2.     {
    3.         return Physics2D.OverlapBox(rightBound.position + frontSensor.center, frontSensor.size, 0, groundLayer);
    4.     }