Raycast2D always always hits something

Hello I am trying to make a isGrounded check for jumping for a 2D platformer. My rays come out from the bottom corners of boxcollider2D and their lengths are the half of my collider box towards bottom. I have put a debug with the same parameters to see it it hits anything but when I keep pressing jump it keeps going up and grounded is always true. When I put a layermask to the ground it didn’t jump at all and was never grounded even on the ground. My code is below

Vector2 extent = GetComponent<BoxCollider2D>().size*0.5f;
        Vector2 bottomleft = new Vector2(GetComponent<BoxCollider2D>().bounds.min.x, GetComponent<BoxCollider2D>().bounds.min.y);
        Vector2 bottomright = new Vector2(GetComponent<BoxCollider2D>().bounds.max.x, GetComponent<BoxCollider2D>().bounds.min.y);

        RaycastHit2D groundedleft = Physics2D.Raycast(bottomleft, Vector2.down, extent.y);
        RaycastHit2D groundedright = Physics2D.Raycast(bottomright, Vector2.down, extent.y);
        Debug.DrawRay(bottomright, Vector2.down * extent.y, Color.green);
        Debug.DrawRay(bottomleft, Vector2.down * extent.y, Color.green);
        if (Input.GetKey("up") && groundedleft.collider !=null && groundedright.collider !=null)
            grounded = true;

Those RaycastHit2D objects you’re getting back from the Raycast calls contain lots of helpful information. You should probably ask them what they hit to verify it’s what you expect.

For instance, you can use:


You probably want to only jump if the “up” key is pressed and the RaycastHit2D objects have hit an “appropriate” object.

With no layermask it was probably reading the character. With the layermask it probably wasn’t probing far enough. You usually want to add a little bit to the length of the array. If it only goes to the extent of the collider then it wont actually find the ground collider.

Add a layer mask back in.
Add a very small value to your array’s length, depends on scaling for how large this value should be.

Double check your layers.

Beyond that, I would suggest checking (groundedLeft || groundedRight), I imagine it would be frustrating if your character is barely hanging off an edge and you can’t jump because of it.

Lastly, you aren’t using your grounded variable, but why are you setting the boolean true once the player jumps? Seems misplaced.