user6777878
user6777878

Reputation:

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 = Color.green; Gizmos.DrawLine(from, to); }
    else { Gizmos.color = Color.red; 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

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

Example when it's not OK

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

I have set BoxCollider2D and my Layer on wall cell.

Upvotes: 3

Views: 182

Answers (1)

Foggzie
Foggzie

Reputation: 9821

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) ? Color.green : Color.red;
Gizmos.DrawLine(from, to);

Upvotes: 1

Related Questions