确定两点是否接近

时间:2012-10-23 14:07:11

标签: c# .net vb.net math

我有以下内容:

bool AreNear(Point Old, Point Current)
{
    int x1 = Convert.ToInt32(Old.X);
    int x2 = Convert.ToInt32(Current.X);
    int y1 = Convert.ToInt32(Old.Y);
    int y2 = Convert.ToInt32(Current.Y);
    if (x1 == x2) {
        if (y1 == y2) {
            return true;
        }
    }
    return false;
}

如果当前点位于旧点的25像素半径内,我想在函数中返回true。谁能告诉我怎么做?

4 个答案:

答案 0 :(得分:15)

您可以使用the Pythagorean formula计算两点之间的距离。在C#中:

var d = Math.Sqrt(Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)) 

为什么这样做?请看下面的图表,并记住a^2 + b^2 = c^2适用于直角三角形:

Pythagoras

答案 1 :(得分:4)

使用毕达哥拉斯定理计算距离的平方,并与半径的平方进行比较:

bool ComparePoints(Point Old, Point Current)
{
    int x1 = Convert.ToInt32(Old.X);
    int x2 = Convert.ToInt32(Current.X);
    int y1 = Convert.ToInt32(Old.Y);
    int y2 = Convert.ToInt32(Current.Y);
    int dx = x1 - x2;
    int dy = y1 - y2;
    return (dx*dx + dy*dy) < 25*25;
}

答案 2 :(得分:3)

您可以使用Math.Abs来获取距离:

public static bool InDistance(Point Old, Point Current, int distance)
{
    int diffX = Math.Abs(Old.X - Current.X);
    int diffY = Math.Abs(Old.Y - Current.Y);
    return diffX <= distance && diffY <= distance;
}

使用它:

bool arePointsInDistance = InDistance(new Point(100, 120), new Point(120, 99), 25);

答案 3 :(得分:0)

尝试使用距离公式http://www.purplemath.com/modules/distform.htm并比较距离&lt; = 25