unity-game-engine

Raycast not detecting the collision when hitting ground


I have a ground object that has a Collider2D attached to the ground game object, this game object has a layer name of "Ground". I have a player object that walks on the ground but when the player moves in the air to fall on the ground the collision does not occur using the Raycast:

Here is the code in the fixed update:

    Debug.DrawRay(transform.position, transform.TransformDirection(-Vector2.up) * 0.7f, UnityEngine.Color.red);

    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(-Vector2.up), 0.7f);

    // If it hits something...
    if (hit && hit.transform.gameObject != gameObject && hit.transform.gameObject.layer == LayerMask.NameToLayer("Ground"))
    {
        Debug.Log("Hit " + hit.transform.gameObject.tag);
    }

Here is the DrawRay inside the game when viewing the scene:

enter image description here

You can see the raycast of the red colour which is intersecting the player and the ground.

Where am I going wrong.

When i remove "&& hit.transform.gameObject.layer == LayerMask.NameToLayer("Ground")",

I get a hit when the player is on top of the ladder and moves down from the ladder.


Solution

  • Well hitting the player layer in the first place makes little sense

    You also only got one single hit and discard potential others

    => If you hit the player you ignore it. If eventually you also hit the ground at the same time remains undedected!

    You rather want to use a proper LayerMask in order to only check/hit those layers (Ground) you are actually interested in!

    public LayerMask groundLayers;
    
    ...
    
    RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.TransformDirection(-Vector2.up), 0.7f, groundLayers);
    

    Might also be interested in using my SingleLayer implementation. It is basically a dropdown similar to the LayerMask with the difference that it is for only a single layer instead of a mask