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:
- The Player presses Jump
- The player has non-0 y velocity and is currently marked as grounded
- 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.