Line of Sight

Typically, my foray into trying to detect line of sight using 2D objects turned into a misadventure. It turns out that Unity only does 2D in the x, y plane and this matters because my entire world has Up in the Y axis and thus my entire world is rendered along the x, z plane.

But hope was not lost, it turns out that for all my GameObjects that needed some 2D collision checks but already had a 3D collision mesh added to it, I could attach a child GameObject and then add a PolygoneCollider2D to that (you can’t have 2D and 3D collision meshes attached to the same GameObject).

The result (if you look at the Scene view) is a perpendicular world where all the 2D collision polygons are visible along the x, y plane. It doesn’t matter though because after some Vector3 to Vector2 conversions are done, a 2D Raycast works just fine and the collisions are detected. The Vector2 can then be converted back to Vector3 and then used for whatever purpose that was intended. Phew. Why is this important? Well, I got a line of sight indicator working for when making a unit target something and I figured 2D checks would be cheaper to calculate. Here’s a screenshot.

Marvel at my awesome placeholder UI (and just ignore the fact that some tanks have been randomly placed in the water).