【问题标题】:Many Vectors, find closest 4 to object许多向量,找到最接近对象的 4 个
【发布时间】:2015-04-22 20:40:41
【问题描述】:

我有 Vector3 数组:

public Vector3[] positions;

我有这个对象的对象和位置存储在 Vector3 变量中。

我有第二个 Vector3 数组:

public Vector3[] four;

我需要从数组 positions 中找到距离对象最近的 4 个向量,并将它们放入数组 four 中。

我想了几个小时怎么做,但我真的不知道怎么做。请给我一些想法(请在 C# 中)。

【问题讨论】:

  • 那么你做什么呢?你能计算出两个位置之间的距离吗?你能创建一个向量和一个距离的匿名对象吗?您可以按距离对列表进行排序吗?你能选前四个吗?

标签: c# unity3d


【解决方案1】:

这应该可行。它计算 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];
      }
   }
}

【讨论】:

  • 描述一下,你的代码应该做什么,你期望什么结果或者你的问题是什么?
  • 这段代码应该可以解决 UareBugged 提出的问题
  • 对不起,这是一个错误...无论如何,请剪下你的代码并进行描述..
  • @Phoenix 没问题 :) 代码中已经有几个 cmets。你要我解释哪一行?
  • 这里有一些建议:stackoverflow.com/help/how-to-answer 当答案不仅包含代码和 cmets,而且还包含一些解释您做什么和做什么时,那就太好了。..
猜你喜欢
  • 1970-01-01
  • 2011-02-22
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 2023-03-06
相关资源
最近更新 更多