【问题标题】:How to find the nearest Vector from a default Position?如何从默认位置找到最近的向量?
【发布时间】:2014-03-04 01:15:12
【问题描述】:

在我的 C# 项目中,我有一个 Vector3 数组。现在我想从相机位置找到最近的 Vector3。相机的位置也是一个 Vector3 对象。我该怎么做?

感谢您的帮助!

【问题讨论】:

    标签: c# vector directx


    【解决方案1】:

    我认为您可以将向量彼此相减以获得向量的长度(幅度)

    Vector3 v1 = new Vector3(1,2,3);
    Vector3 v2 = new Vector3(1,1,1);
    
    Vector3 difference= new Vector3(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z)
    
    float distance = Math.Sqrt(
       Math.Pow(difference.x, 2f) +
       Math.Pow(difference.y, 2f) +
       Math.Pow(difference.z, 2f));
    

    然后你可以像上面的代码那样从坐标的幂中获取sqrt来计算距离。

    如果您愿意,可以使用扩展方法

    public static class Extensions
    {
        public static double Distance(this Vector3 source, Vector3 target)
        {
            var difference = new Vector3(source.X - target.X, source.Y - target.Y, source.Z - target.Z);
    
            var distance = Math.Sqrt(
                    Math.Pow(difference.X, 2f) +
                    Math.Pow(difference.Y, 2f) +
                    Math.Pow(difference.Z, 2f)
                );
    
            return distance;
        }
    }
    

    我不确定它是否有效,因为我是用 notepad++ 编写的 :)

    【讨论】:

      【解决方案2】:

      您可以在循环中使用 Vector3.Distance(camera, otherObject),将距离最近的对象保留在临时变量中,即

      long closestDistance = -1;
      Vector3 closestVector = null;
      
      for(Vector3 otherVector : myCollection)
      {
          long thisDistance = Vector3.Distance(camera, otherVector);
      
          if (thisDistance < closestDistance || closestDistance == -1)
          {
             closestDistance = thisDistance;
             closestVector = otherVector;
          }
      }
      

      【讨论】:

      • 也可以为此创建一个扩展方法。如果它不存在
      猜你喜欢
      • 2015-01-10
      • 2011-02-22
      • 2014-01-17
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      相关资源
      最近更新 更多