Having a list of points, how do I find if they are in clockwise order?
For example:
point[0] = (5,0)
point[1] = (6,4)
point[2] = (4,5)
point[3] = (1,5)
point[4] = (1,0)
would say that it is anti-clockwise (or counter-clockwise, for some people).
If you use Matlab, the function
ispolycw
returns true if the polygon vertices are in clockwise order.Solution for R to determine direction and reverse if clockwise (found it necessary for owin objects):
I think in order for some points to be given clockwise all edges need to be positive not only the sum of edges. If one edge is negative than at least 3 points are given counter-clockwise.
My C# / LINQ solution is based on the cross product advice of @charlesbretana is below. You can specify a reference normal for the winding. It should work as long as the curve is mostly in the plane defined by the up vector.
with a unit test
Another solution for this;
Take all the vertices as an array like this;
I guess this is a pretty old question, but I'm going to throw out another solution anyway, because it's straightforward and not mathematically intensive - it just uses basic algebra. Calculate the signed area of the polygon. If it's negative the points are in clockwise order, if it's positive they are counterclockwise. (This is very similar to Beta's solution.)
Calculate the signed area: A = 1/2 * (x1*y2 - x2*y1 + x2*y3 - x3*y2 + ... + xn*y1 - x1*yn)
Or in pseudo-code:
Note that if you are only checking the ordering, you don't need to bother dividing by 2.
Sources: http://mathworld.wolfram.com/PolygonArea.html