# Finding if 2 polygons intersect using clipper library

After realising my code was pretty inefficient at checking for polygon overlaps, I've turned to a mentioned library Clipper but finding it difficult to know hot to use it for this operation.

I am using unity Vector2[] for my shape descriptions:

//Square
Vector2[] square = new Vector2[] {
new Vector2(0,0),
new Vector2(1,0),
new Vector2(1,1),
new Vector2(0,1)
};


I want to be able to do the above boolean comparison of 2 shapes. If anyone knows Clipper well, what methods can I use to do this check?

I've recently tried the following but the result is always true even when the test shapes are completely separate from each other:

public bool CheckForOverLaps(Vector2[] shape1, Vector2[] shape2) {

List<IntPoint> shape1IntPoints = Vector2ArrayToListIntPoint (shape1);
List<IntPoint> shape2IntPoints = Vector2ArrayToListIntPoint (shape2);

List<List<IntPoint>> solution = new List<List<IntPoint>> ();

c.AddPath (shape1IntPoints, PolyType.ptSubject, true);
c.AddPath (shape2IntPoints, PolyType.ptClip, true);
c.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);
return solution.Count != 0;

}

private List<IntPoint> Vector2ArrayToListIntPoint (Vector2[] shape) {

List<IntPoint> list = new List<IntPoint> ();

foreach (Vector2 v in shape) {

list.Add (new IntPoint (v.x, v.y));

}

return list;

}


And the tests:

    //Square
Vector2[] square = new Vector2[] {
new Vector2(0,0),
new Vector2(2,0),
new Vector2(2,2),
new Vector2(0,2)
};

//Square
Vector2[] square2 = new Vector2[] {
new Vector2 (1, 1),
new Vector2 (3, 1),
new Vector2 (3, 3),
new Vector2 (1, 3)
};

//Square
Vector2[] square3 = new Vector2[] {
new Vector2 (2, 0),
new Vector2 (4, 0),
new Vector2 (4, 2),
new Vector2 (2, 2)
};

//Square
Vector2[] square4 = new Vector2[] {
new Vector2 (4, 0),
new Vector2 (6, 0),
new Vector2 (6, 2),
new Vector2 (4, 2)
};

Assert.IsTrue(tc.CheckForOverLaps(square,square2));
Assert.IsFalse(tc.CheckForOverLaps(square,square3));
Assert.IsFalse(tc.CheckForOverLaps(square,square4));


Many thanks.

## 1 Answer

I got this in the end.. I had to Clear() out clipper for the next tests to work. Converted everything to IntPoint before hand to improve efficiency.

public bool CheckForOverLaps(List<IntPoint> shape1, List<IntPoint> shape2) {

clipper.Clear();
solution.Clear ();

clipper.AddPath (shape1, PolyType.ptSubject, true);
clipper.AddPath (shape2, PolyType.ptClip, true);
clipper.Execute (ClipType.ctIntersection, solution, PolyFillType.pftNonZero, PolyFillType.pftNonZero);

return solution.Count != 0;
}