我有 Vector3 数组:
public Vector3[] positions;
我将对象和该对象的位置存储在 Vector3 变量中。
我有第二个 Vector3 数组:
public Vector3[] four;
我需要从数组 positions 中找到距离该对象最近的 4 个向量,并将它们放入数组 four 中。
我花了几个小时思考如何做到这一点,但我真的不知道该怎么做。请给我一些想法(请使用 C#)。
最佳答案
这应该有效。它计算 myObject 和所有位置之间的所有距离,并将它们与位置索引存储在一起。
然后根据距离对结果进行排序。
最后,它获取前 4 个结果并使用存储的索引来获取正确的位置。
using UnityEngine;
using System.Collections.Generic;
public class Distance
{
public float distance;
public int index;
public Distance( float distance, int index )
{
this.distance = distance;
this.index = index;
}
}
class MyGame
{
Vector3[] positions;
Vector3 myObject;
Vector3[] four = new Vector3[4];
List<Distance> distanceList = new List<Distance>();
void Foo()
{
for( int i = 0; i < positions.Length; i++ )
{
// get all the distances
float distance = Vector3.Distance( positions[i], myObject );
// store the distance with the index of the position
distanceList.Add( new Distance( distance, i ) );
}
// sort the distances
distanceList.Sort( delegate (Distance t1, Distance t2) { return (t1.distance.CompareTo(t2.distance)); } );
for( int i = 0; i < 4; i++ )
{
// get the first four sorted distances
int idx = distanceList[i].index;
// use the stored index
four[i] = positions[idx];
}
}
}
关于c# - 许多向量,找到最接近对象的 4 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590137/