isOnGround()

private bool isOnGround()
    {
        float extraHeight = 0.1f; //because sometimes the exact bottom miscalculates
        Vector3 front = new Vector3(polygonCollider2D.bounds.min.x, polygonCollider2D.bounds.center.y, 0);
        Vector3 back = new Vector3(polygonCollider2D.bounds.max.x, polygonCollider2D.bounds.center.y, 0);
        //start ray                  //direction   //length (1/2 the height of the character)        //check against this layer
        RaycastHit2D raycastHit = Physics2D.Raycast(polygonCollider2D.bounds.center, -Vector2.up, polygonCollider2D.bounds.extents.y + extraHeight, groundLayerMask);
        RaycastHit2D raycastHit2 = Physics2D.Raycast(front, -Vector2.up, polygonCollider2D.bounds.extents.y + extraHeight, groundLayerMask);
        RaycastHit2D raycastHit3 = Physics2D.Raycast(back, -Vector2.up, polygonCollider2D.bounds.extents.y + extraHeight, groundLayerMask);

        Color rayColor;

        if (raycastHit.collider != null || raycastHit2.collider != null || raycastHit3.collider != null)
        {
            rayColor = Color.green;
        }
        else
        {
            rayColor = Color.red;
        }
        //draw ray on screen when Gizmos enabled
        Debug.DrawRay(polygonCollider2D.bounds.center, -Vector2.up * (polygonCollider2D.bounds.extents.y + extraHeight), rayColor);
        Debug.DrawRay(front, -Vector2.up * (polygonCollider2D.bounds.extents.y + extraHeight), rayColor);
        Debug.DrawRay(back, -Vector2.up * (polygonCollider2D.bounds.extents.y + extraHeight), rayColor);
        if (raycastHit.collider != null)
        {
            return raycastHit.collider != null;
        }
        else if (raycastHit2.collider != null)
        {
            return raycastHit2.collider != null;
        }
        else if (raycastHit3.collider != null)
        {
            return raycastHit3.collider != null;
        }
        else
        {
            return raycastHit.collider != null;
        }

    }


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *