Spherecast/linecast in 2.5D (line of sight checks)

I have a 2.5D game world whereby the world is flat but I use a 3D camera angle to view it.

The world is populated with 2D complex polygons that are rendered at y=0 and have an associated collision mesh at y=0. I would like to calculate line of sight by casting a line at y=0 and checking if it intercepts any of the polygons.

I’ve tried a SphereCast and a LineCast and none seem to work if I try to cast with lines that have endpoints at y=0. If the end points of each cast is say, at y=10 and y=-10 then the collision is detected so it seems that the collision is only detected if going at a 3D orientation.

Does anyone have an alternative suggestion. I was using the following code.

//p1.y = 10;
//p2.y = -10;
Vector3 dir = p2 - p1;
int layerMask = 1 << LayerMask.NameToLayer("Obstacles");

if (Physics.SphereCast(p1, 4.0f, dir, out hit, dir.magnitude, layerMask)) {
	Debug.Log ("*** NO LINE OF SIGHT ***");
}
else {
	Debug.Log ("*** CLEAR SHOT ***");
}

I’m going to edit my previous answer and clarify what I’ve done for this which is…

  • Made a child GameObject for each of my GameObjects that contain the complex 2D polygons (that populate my 3D game world)
  • Added a PolygonCollider2D component to the child GameObject. By doing this, the parent GameObject can have a 3D Mesh Collider that can be used for other purposes such as with the A* library I’m using.
  • I assigned all child game objects with the PolygonCollider2D to a “Colliders2D” layer.

If you view the world in 2D scene view with the PolgyonCollider2D gizmos showing all the lines, you get to see the 2D world drawn perpendicular to the 3D world where Y is up.

With the above setup I can do a Physics2D.Linecast on the “Colliders2D” layer to determine collisions.