Physics2D.Raycast is fine, I'm an idiot

Currently trying to get a ground hit detection system working with Raycast(). This is my current progress:

public bool isGrounded {
    		get{
    			LayerMask mask = (1 << LayerMask.NameToLayer ("Terrain"));
    
    			RaycastHit2D hit = Physics2D.Raycast (transform.position, Vector3.down, 2, mask);
    			Debug.DrawRay (transform.position, Vector3.down, Color.green);

    			// If RaycastHit2D.collider is not Null
    			if (hit.collider != null) {
    				Debug.Log ("Raycast Collider not Null");

    				// Check max grounded distance
    				if (Vector2.Distance (hit.point, transform.position) < 0.5f) {
    					Debug.Log ("Raycast Collider Tag: " + hit.collider.tag);

    					// Return whether the hit collider is a Platform or not
    					return hit.collider.CompareTag ("Platform");
    				} 

    				// Player is not grounded, return false.
    				else {
    					Debug.Log ("Player is not Grounded");
    					return false;
    				} 
    			} else {
    				Debug.Log("Collider is Null or Did not hit anything");
    				return false;
    			}
    		}
    	}

The intended use for this is to be called in one of three locations to check if the player is grounded:

  1. The Player presses Jump
  2. The player has non-0 y velocity and is currently marked as grounded
  3. The player has 0 y velocity and is currently marked as not grounded

Not a fool-proof system, but it should handle most cases while I work on other things. My issue is that the Raycast always returns the player object as being hit despite it being on a layer different from the one specified. And if I switch my Player object to Layer:IgnoreRaycast, the Raycast hits nothing despite there being a large Edge Collider 2D below my character. I’ve tried substituting it with a box collider as well and it still isn’t seen by the Raycast(). All of my platforms are marked as Layer:Terrain, Tag:Platform.


OK, I figured out my issue. Aside from overusing the term Player and getting really confused, I forgot to account for the size offset of the Player’s boxcollider2D.

LayerMask.NameToLayer returns the layer index. You need to pass a Layer Mask to Raycast, so use LayerMask.GetMask.

Edit: Upon rereading your code, it looks like you’re using the index to create the mask. Seems like that should work too, but try using GetMask to see if that helps.

Have you tried increasing the max ray length?

I would Debug.Log hit.point to see where this false detection is occuring. It might show an inconsistency enough to determine that OP has a forgotten script at work or something to that effect.