Physics2D.Raycast is returning null randomly

I have a board with cells, some are normal and some are walls. I would like to set a line between two points and know if it's colliding with a wall cell.

Here is my code:

private void OnDrawGizmosSelected()
    RaycastHit2D raycast = Physics2D.Raycast(from, to, Vector2.Distance(from, to), layerMask);
    if (raycast.collider == null) { Gizmos.color =; Gizmos.DrawLine(from, to); }
    else { Gizmos.color =; Gizmos.DrawLine(from, to); }

It works 80% of the time. At certain points in the map it's not working at all.

Example when it's OK

In this case it's ok, but if I go down my bottom right point for about 0.2, it's not working anymore.

Example when it's not OK

My line pass green like there are no wall at all...

Ofc I have set BoxCollider2D and my Layer on wall cell.

Do you guys have any idea of what's going on here ?

Thank you !


1 Answers Physics2D.Raycast is returning null randomly

The second argument in Physics2D.Raycast() is the "direction," not the end of the ray (unlike Gizmos.DrawLine(), which you are calling properly because it does use a start and end as arguments). You want something like this:

Vector2 direction = to - from;
Physics2D.Raycast(from, direction.normalized, direction.magnitude, layerMask);

You've also got some duplicated code in your proceeding if statement that could be cleaned up:

Gizmos.Color = (raycast.collider == null) ? :;
Gizmos.DrawLine(from, to);

1 weeks ago