Следующая функция представляет собой метод сравнения для сравнения двух векторов, на которые вы сможете ссылаться в List.Sort
методе
Прежде всего, сравнивается, совпадают ли векторы.
Затем он сравнивает y
компоненты и, наконец, сравнивает угол вектора на плоскости (XZ)
.
public static int Compare( Vector3 v1, Vector3 v2 )
{
// Comparing two vectors this way is fine
// Unity has overloaded the == operator
// So as to avoid floating point imprecision
if ( v1 == v2 ) return 0;
if ( Mathf.Approximately( v1.y, v2.y ) )
{
float magnitude1 = v1.magnitude;
float magnitude2 = v2.magnitude;
if ( Mathf.Approximately( magnitude1, 0 ) ) return -1;
if ( Mathf.Approximately( magnitude2, 0 ) ) return 1;
// I took opposite coordinates because I had
// "better" results, meaning the "smallest" angle would be
// associated to the vector closer to the (1,0,0) vector
// with an anti clock-wise rotation
float angle1 = Mathf.Atan2( -v1.z, -v1.x );
float angle2 = Mathf.Atan2( -v2.z, -v2.x );
if ( Mathf.Approximately( angle1, angle2 ) ) return 0;
return angle1 > angle2 ? 1 : -1;
}
return v1.y > v2.y ? 1 : -1;
}
Вот небольшой фрагмент, чтобы добавить некоторые элементы в вид сцены, чтобы увидеть векторы.
#if UNITY_EDITOR
private void OnDrawGizmosSelected()
{
Vector3 origin = Vector3.zero;
Gizmos.color = new Color( 1, 1, 1, 0.2f );
for( int i = 0 ; i < Vectors.Count ; ++i )
{
Gizmos.DrawLine( origin, Vectors[i] );
UnityEditor.Handles.Label( Vectors[i], i.ToString() );
if( i < Vectors.Count - 1 )
DrawGizmoArrow( Vectors[i], Vectors[i + 1], Color.HSVToRGB( (float) i / Vectors.Count, 1, 1 ) );
}
}
private void DrawGizmoArrow( Vector3 start, Vector3 end, Color color )
{
if ( end == start ) return;
Color c = Gizmos.color;
Gizmos.color = color;
Gizmos.DrawLine( start, end );
Vector3 right = Quaternion.LookRotation( end - start ) * Quaternion.Euler(0, 180 + 20, 0) * new Vector3( 0, 0, 1 );
Vector3 left = Quaternion.LookRotation( end - start ) * Quaternion.Euler(0, 180 - 20, 0) * new Vector3( 0, 0, 1 );
Gizmos.DrawRay( end, right * 0.25f );
Gizmos.DrawRay( end, left * 0.25f );
Gizmos.color = c;
}
#endif