using System.Collections.Generic;
//using System.Numerics;
using UnityEngine;
///
/// ClockwiseComparer provides functionality for sorting a collection of Vector2s such
/// that they are ordered clockwise about a given origin.
///
public class ClockwiseComparer : IComparer
{
private Vector2 m_Origin;
///
/// Gets or sets the origin.
///
/// The origin.
public Vector2 origin { get { return m_Origin; } set { m_Origin = value; } }
///
/// Initializes a new instance of the ClockwiseComparer class.
///
/// Origin.
public ClockwiseComparer(Vector2 origin)
{
m_Origin = origin;
}
///
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
///
/// First.
/// Second.
public int Compare(Vector2 first, Vector2 second)
{
return IsClockwise(first, second, m_Origin);
}
///
/// Returns 1 if first comes before second in clockwise order.
/// Returns -1 if second comes before first.
/// Returns 0 if the points are identical.
///
/// First.
/// Second.
/// Origin.
public static int IsClockwise(Vector2 first, Vector2 second, Vector2 origin)
{
if (first == second)
return 0;
Vector2 firstOffset = first - origin;
Vector2 secondOffset = second - origin;
float angle1 = Mathf.Atan2(firstOffset.x, firstOffset.y);
float angle2 = Mathf.Atan2(secondOffset.x, secondOffset.y);
if (angle1 < angle2)
return -1;
if (angle1 > angle2)
return 1;
// Check to see which point is closest
return (firstOffset.sqrMagnitude < secondOffset.sqrMagnitude) ? -1 : 1;
}
}