Collider2D.Cast precision

I have a question about Collider2D.Cast function, it seems like while working with small numbers it returns collisions even if there shouldn’t be any. Here is a picture, and some code:

using UnityEngine;

public class test : MonoBehaviour
{
    BoxCollider2D boxCollider;

    void Awake()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }

    void FixedUpdate()
    {
        RaycastHit2D[] hits = new RaycastHit2D[10];
        boxCollider.Cast(Vector2.up, hits, 2f);
        foreach(RaycastHit2D hit in hits)
        {
            if (!hit) break;
            Debug.DrawRay(transform.position, hit.point - hit.centroid, Color.red);
            Debug.DrawLine(hit.centroid, hit.point, Color.yellow);
        }

    }
}

As you can see, |x| distance between two objects is 0.006, but collision is still detected. Is there something like Collider thickness? Also why hit.point - hit.centroid gives point outside of collider? I wanted to check where collision happened on my collider (left, right, up, down), but around the corners its inconsistent (looks like instead i should check for the same but not on a player collider but rather box that was hit, since it looks more precise and then react to that).

I think i found an answer. There is something like: Physics.defaultContactOffset
Default value is 0,01 and you can change it in project settings.

You actually use this method wrongly in your sample code. You completely ignore the return value of the method. This is extremely important. The array that you pass in has 10 pre allocated results. If the method returns a value of 0, none of those 10 results should be processed. The return value tells you how many results the method has been written into the results array. So you can not use a foreach loop here.

The general usecase would look like this:

RaycastHit2D[] hits = new RaycastHit2D[10];
void FixedUpdate()
{
    int hitCount = boxCollider.Cast(Vector2.up, hits, 2f);
    for(int i = 0; i < hitCount; i++)
    {
        RaycastHit2D[] hit = hits *;*

Debug.DrawRay(transform.position, hit.point - hit.centroid, Color.red);
Debug.DrawLine(hit.centroid, hit.point, Color.yellow);
}
}
Note that i’ve declared and created the “hits” array outside the FixedUpdate method. The point of using a pre-allocated array is to avoid constant creation and garbage collection of the array.