- Home /
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 ***");
}
Can 2D colliders be applied to a 3D world where up is the y direction and the 2D meshes are in the x,z plane? $$anonymous$$y world is 3D in that some of my y=0 planes are extruded into 3d (to represent buildings) but a lot are just planes. The colliders themselves are just 2D so it's cheaper to do mouse picking. I see in the Physics2D.Raycast docs http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html that the $$anonymous$$Depth and maxDepth refer to the z direction, but my meshes are in the x,z plane. I'm guessing because I haven't tried it yet, but I'd have thought that trying to make a PolygonCollider2D would result in a collider drawn in the x,y plane rather than the x,z plane. If that's the case, would the only solution be to rerender my entire world so that Up is actually in the z direction?
Answer by GlennNZ · Jul 23, 2014 at 09:53 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613154707im_/https://answers.unity.com/themes/thub/images/avi.jpg)