2013-03-11 56 views

回答

2

我想你可以減去對方向量來獲得向量的長度(幅度)

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來計算距離。

的extensionmethod,如果你想

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; 
    } 
} 

我不知道,如果它的作品,因爲我在記事本++ :)

0

你可以在一個循環中使用Vector3.Distance(相機,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; 
    } 
} 
+0

寫我的Vector3對象不提供的功能距離.. – Maxim 2013-03-11 09:50:17

+0

也可以爲此創建一個擴展方法。如果它不在那裏 – 2014-03-03 16:50:15

相關問題