0
\$\begingroup\$

I am trying to implement jumping in my game. I am casting a ray to know if the player is grounded, and using a Layermask to make it only react with the floor. The code:

groundLayer = LayerMask.NameToLayer("Ground");
RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, 1.0f, groundLayer.value);
Debug.DrawRay(transform.position, Vector2.down * 1.0f, Color.green);
if (hit.collider != null)
    {
        print(collider.name);
        bounds = collider.bounds;

        if (distance < 0.2f)
        {
            grounded = true;
            return true;
        }
        else
        {
            print(collider.name);
            grounded = false;
            return false;
        }
    }
    else
    {
        print("Collider null");
        return false;
    }

I am receiving collider null always. What am I doing wrong?

EDIT:

In case it helps, this is a screenshot of my Unity editor:

Screenshot

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

The problem is in line:

groundLayer = LayerMask.NameToLayer("Ground");

You need to use a bit mask which turns on only the bit associated with that layer:

groundLayer = 1 << LayerMask.NameToLayer("Ground");

Also, if you want to allow more than one layers, you can do so:

groundLayer = (1 << LayerMask.NameToLayer("Ground")) | (1 << LayerMask.NameToLayer("other layer"));
\$\endgroup\$
3
  • \$\begingroup\$ I have edited what you said, and now its jumping, but in print(collider.name) I get "Player", so the ray is colliding with the player, not the floor. Added a print(groundLayer.value) and Im getting 256. Before adding your suggestion, I was getting 8. \$\endgroup\$
    – Fustigador
    Commented Feb 8, 2020 at 17:53
  • \$\begingroup\$ Unity Component class has a property called collider which is in fact a reference to the collider of the GameObject in which the script is attached to (if it has any). You get "Player" because you are printing the name of the collider which is indeed the Player because you have probably attached the script to the Player GameObject. So, you need to print hit.collider.name and not collider.name. \$\endgroup\$ Commented Feb 8, 2020 at 23:24
  • 1
    \$\begingroup\$ True... didn't realized that...as you may imagine I am pretty new to Unity. Thank you for your help. \$\endgroup\$
    – Fustigador
    Commented Feb 8, 2020 at 23:56

You must log in to answer this question.

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