Polygon.Join C# (CSharp) Method

Join() public method

public Join ( Polygon, other ) : Polygon,
other Polygon,
return Polygon,
    public Polygon Join(Polygon other)
    {
        int thisEdgeId = -1;
        int otherEdgeId = -1;
        for (int i=0;i<Length() && thisEdgeId == -1;i++){
            Vector3 thisFrom = Vertex(i);
            Vector3 thisTo = Vertex((i+1)%Length());
            for (int j=0;j<other.Length();j++){
                Vector3 otherFrom = other.Vertex(j);
                Vector3 otherTo = other.Vertex((j+1)%other.Length());
                if ((thisFrom-otherTo).sqrMagnitude < 0.001f && (thisTo-otherFrom).sqrMagnitude < 0.001f){
                    thisEdgeId = i;
                    otherEdgeId = j;
                    break;
                }
            }
        }
        if (thisEdgeId == -1){
            return null;
        }
        Polygon res = new Polygon();
        // add current points
        for (int i=0;i<Length();i++){
            res.vertices.Add(vertices[(i+thisEdgeId+1)%Length()]);
        }
        otherEdgeId=otherEdgeId+2; // skip current since this equals the last vertex of res
        // add vertices from other
        for (int i=0;i<other.Length()-2;i++){
            res.vertices.Add(other.vertices[(i+otherEdgeId)%other.Length()]);
        }

        // remove any edge (where two edges share endpoints but has different directions
        for (int i=0;i<res.Length();i++){
            var thisVert = res.Vertex(i);
            var nextNextVert = res.Vertex((i+2)%res.Length());
            bool almostEqual = (thisVert - nextNextVert).sqrMagnitude < 0.001f;
            if (almostEqual){
                var vects = new int[]{(i+1)%res.Length(),i};
                System.Array.Sort(vects);
                res.vertices.RemoveRange(vects[1],1);
                res.vertices.RemoveRange(vects[0],1);
                i = i+2;
            }
        }

        return res;
    }