- Home /
Vector2 array sort clockwise
So I have an array of Vector2s but these are in the wrong order. I need to have them clockwise to generate a mesh based on these coords.
Is there a quick way of doing this?
Answer by VesuvianPrime · Jan 15, 2015 at 01:13 PM
I wrote the following comparer to do this:
You can use it in array sort methods to reorder the points to clockwise.
Edit:
I used @ArkaneX's answer to tidy mine a little: http://pastebin.com/1RkaP28U
My solution handles an origin offset, as well as points that occupy the same angle from the origin.
The return values are flipped in your IsClockwise function but other than that thanks!
Answer by MachinesOfN · Sep 10, 2015 at 02:31 PM
The above isn't quite right. The trig solution below is a bit cleaner and more accurate.
public class ClockwiseVector3Comparer : IComparer<Vector3>
{
public int Compare(Vector3 v1, Vector3 v2)
{
return Mathf.Atan2(v1.x, v1.z).CompareTo(Mathf.Atan2(v2.x, v2.z));
}
}
Actually the accepted answer is more correct. First of all you're dealing with Vector3 values, not Vector2. You only loop at the x-z plane and not the 2d x-y plane.
Also this basically the same as the solution in the accepted answer but less flexible. The points need to be located around the origin in order to properly sort them. The accepted solution allows to specify a center point.
Good points! I guess I was just lucky because I wanted something real quick to match the user defined points into a polygon clockwise and my code had already Vector3 and the points aligned along the same x-z plane (on the surface of the room floor in my AR app). So this was the quickest copy-paste solution in my case lol. But at least I know where to look if I experience any issue due to the origin thing. Thanks!
Answer by ArkaneX · Jan 15, 2015 at 01:10 PM
To achieve this, you need custom comparer, which you can pass to sort method. C# example:
public class ClockwiseVector2Comparer : IComparer<Vector2>
{
public int Compare(Vector2 v1, Vector2 v2)
{
if (v1.x >= 0)
{
if (v2.x < 0)
{
return -1;
}
return -Comparer<float>.Default.Compare(v1.y, v2.y);
}
else
{
if (v2.x >= 0)
{
return 1;
}
return Comparer<float>.Default.Compare(v1.y, v2.y);
}
}
}
and then sort using the above comparer:
Array.Sort(vectorArray, new ClockwiseVector2Comparer());
Please note, that above comparer is very basic. For example, it assumes that center of your 'clock' is (0,0) and will not sort vectors with the same direction (and vector (0,0)).
Oh cool, I didn't realize IComparer could be generic!
$$anonymous$$y Visual Studio says it's a non-generic type. Am I doing something wrong?
Your answer
![](https://koobas.hobune.stream/wayback/20220613180453im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Matching Index of two Arrays after one Array is sort 3 Answers
Sorting builtin arrays 2 Answers
Sorting Array 1 Answer
Extend Unity ObjectField / Array function/Gui interface 1 Answer