[英]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.