# Check whether a polygon is complex for Unity3D/C#

Story: A player in a game shall dynamically create a fence by placing some poles.

A wire is attached to the poles from the very beginning. To avoid any intersections of the wire, the polygon (fence) built by the poles must be either convex or concave. The situation of a complex polygon must be avoided, otherwise it will lead into a short circuit.

Using the Faster Line Segment Intersection algorithm from a previous post, the implementation is rather simple by checking all connections for intersections.

```static bool IsPolygonComplex(Vector2[] polygon) {   for (int i = 0; i < polygon.Length - 2 ; i++) {   int n = i + polygon.Length - 2;   if (i >= 2) { n -= (i - 1); }   for (int j = i + 2; j <= n; j++) { if (FasterLineSegmentIntersection(polygon[i], polygon[i+1], polygon[(j)%polygon.Length], polygon[(j+1)%polygon.Length])) { return true; } } }   return false; }```

Note: It’s very possible, that this rather empirical solution is not the optimal algorithm. So if you know it, please drop a note.

```static bool FasterLineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) {   Vector2 a = p2 - p1; Vector2 b = p3 - p4; Vector2 c = p1 - p3;   float alphaNumerator = b.y*c.x - b.x*c.y; float alphaDenominator = a.y*b.x - a.x*b.y; float betaNumerator = a.x*c.y - a.y*c.x; float betaDenominator = alphaDenominator; /*2013/07/05, fix by Deniz*/   bool doIntersect = true;   if (alphaDenominator == 0 || betaDenominator == 0) { doIntersect = false; } else {   if (alphaDenominator > 0) { if (alphaNumerator < 0 || alphaNumerator > alphaDenominator) { doIntersect = false; } } else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator) { doIntersect = false; }   if (doIntersect && betaDenominator > 0) { if (betaNumerator < 0 || betaNumerator > betaDenominator) { doIntersect = false; } } else if (betaNumerator > 0 || betaNumerator < betaDenominator) { doIntersect = false; } }   return doIntersect; }```