[英]How do I calculate the distance between two squares on a grid, including the target square
我一直在嘗試對以下代碼進行變體...
public int Distance2D(int x1, int y1, int x2, int y2)
{
// ______________________
//d = √ (x2-x1)^2 + (y2-y1)^2
//
//Our end result
int result = 0;
//Take x2-x1, then square it
double part1 = Math.Pow((x2 - x1), 2);
//Take y2-y1, then sqaure it
double part2 = Math.Pow((y2 - y1), 2);
//Add both of the parts together
double underRadical = part1 + part2;
//Get the square root of the parts
result = (int)Math.Sqrt(underRadical);
//Return our result
return result;
}
下面的例子是為了清楚起見,但由於我的錯誤而錯誤
Distance2D(1, 1, 1, 2) // 返回 1 - 正確
Distance2D(1, 1, 2, 1) // 返回 1 - 正確
Distance2D(1, 1, 2, 2) // 返回 1 - 正確
Distance2D(1, 1, 5, 5) // 返回 5 - 正確
Distance2D(0, 2, 5, 8) // 返回 7 - 不正確,應該是 8
Distance2D(1, 1, 5, 3) // 返回 4 - 不正確,應該是 5
Distance2D(10, 112, 15, 118) // 返回 7 - 不正確,應該是 8
有沒有更好的公式?
由於錯誤地從第一個坐標的位置取第二個坐標的原點,我的一些預期值不正確。
我試圖獲得一個游戲塊在方形網格上從一個坐標移動到另一個坐標所需的移動次數。 一次移動一格,對角線也算作 1 次移動。
因此 ...
如果我在結果上使用Math.Round()
那么我會得到以下錯誤......
如果我使用Math.Ceiling()
我會收到以下錯誤...
問題是執行.99999
( (int)
) 有效地對您的數字執行“地板”操作,切斷任何十進制值,即使這些十進制值是.99999
。 聽起來您希望將值四舍五入到最接近的整數,這可以使用Math.Round()
函數來完成。
嘗試這個:
result = (int)Math.Round(Math.Sqrt(underRadical));
您采用的基於勾股定理的方法不適用於您要計算的內容。 這是一個完全不同的用例。 好消息是,您的用例要簡單得多。 只需計算出您必須在每個軸上行駛的距離,然后減去您可以通過對角移動來走的任何捷徑。 像這樣的事情,我認為:
var yDist = Math.Abs(y2 - y1);
var xDist = Math.Abs(x2 - x1);
var diagShortcut = Math.Min(yDist, xDist);
return yDist + xDist - diagShortcut;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.