Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question IsGrounded returns true when colliding with wall

Discussion in '2D' started by jaaka770, Oct 17, 2023.

  1. jaaka770

    jaaka770

    Joined:
    Sep 4, 2023
    Posts:
    5
    Hello,
    I am confused on why my IsGrounded function sometimes returns true when the player collides with a vertical wall and if there is an easy way to fix that:

    private bool IsGrounded()
    {
    // Moves a boxcast downward to see if it collides with ground layer
    return Physics2D.BoxCast(box.bounds.center, box.bounds.size, 0f, Vector2.down, 0.1f, ground);
    }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,776
    It returns true then because the query you're using is contacting the wall. It cannot be anything else.

    The above just looks like examples/tutorials you see all over the place and it's an absolute awful way of doing it but there's nothing I can do to remove such information.

    The problem being that often it's a collider that's dedicated for this and it's not related to the colliders being used by the actual character. Also, you have to position the collider in a certain way at a certain location relative to the character and specify a certain distance. All this is artificial! Also, trying to read the details of an existing collider using its (approximate) bounds then pass them to a query when you can simply use the collider (abstractly) to do the cast/overlap with:

    https://docs.unity3d.com/ScriptReference/Collider2D.OverlapCollider.html
    https://docs.unity3d.com/ScriptReference/Collider2D.Cast.html

    The best way though to detect if you're touching something is to ask the physics system if there are contacts on any colliders on a Rigidbody2D or on a specific Collider2D. You can filter them by layer(s) and even the direction the contact normal is. You can see this here:



    The test in the video is checking for any contact from below without a certain angle range. The check comes down to a single line of code: https://github.com/Unity-Technologi...Miscellaneous/SimpleGroundedController.cs#L17

    You can perform checks for walls by changing the angle for instance.