C# 按球体上的位置对矢量3排序
我有一个向量列表,它们是球体表面上的顶点。我想对它们进行分类,使它们从球体的南极开始,然后螺旋上升到北极C# 按球体上的位置对矢量3排序,c#,unity3d,C#,Unity3d,我有一个向量列表,它们是球体表面上的顶点。我想对它们进行分类,使它们从球体的南极开始,然后螺旋上升到北极 我想你可以按y对顶点排序,然后按z和x对它们进行次排序,但我不知道如何在c#中实现这一点。下面的函数是一个比较两个向量的函数,你可以在该方法中引用它们 首先,比较向量是否相同 然后,比较y分量,最后比较(XZ)平面上向量的角度 public static int Compare( Vector3 v1, Vector3 v2 ) { // Comparing two vectors
我想你可以按y对顶点排序,然后按z和x对它们进行次排序,但我不知道如何在c#中实现这一点。下面的函数是一个比较两个向量的函数,你可以在该方法中引用它们 首先,比较向量是否相同 然后,比较
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
\if UNITY\u编辑器
私有无效OnDrawGizmosSelected()
{
矢量3原点=矢量3.0;
Gizmos.color=新颜色(1,1,1,0.2f);
对于(int i=0;i
请参见,以下是完整的解决方案