c# - 许多向量,找到最接近对象的 4 个

标签 c# unity-game-engine

我有 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/

相关文章:

ios - Unity 性能峰值达到 30 FPS

android - Unity Google Play 服务插件 Social.localUser.Authenticate(...) 应用程序崩溃

c# - 如何卸载附加场景?

unity-game-engine - Unity3D 带孔动态网格

c# - 获取所有目录并捕获权限异常并继续

c# 使用静态方法扩展 String 类

c# - XNA 游戏启动的表单中带有 RichTextBox.ScrollToCaret 的 AccessViolationException

c# - 在 C# 中处理 OpenFileDialog?

c# - 没有等待的异步编程?

c# - 让 OnMouseDown 与 2D 多边形碰撞器一起使用