Determine If Two Points Are Near

前端 未结 4 1573
轮回少年
轮回少年 2020-12-20 22:30

I have the following:

bool AreNear(Point Old, Point Current)
{
    int x1 = Convert.ToInt32(Old.X);
    int x2 = Convert.ToInt32(Current.X);
    int y1 = Con         


        
相关标签:
4条回答
  • 2020-12-20 23:04

    You can use Math.Abs to get the distance:

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

    use it:

    bool arePointsInDistance = InDistance(new Point(100, 120), new Point(120, 99), 25);
    
    0 讨论(0)
  • 2020-12-20 23:04

    Try using the distance formula http://www.purplemath.com/modules/distform.htm and compare the distance <=25

    0 讨论(0)
  • 2020-12-20 23:08

    You can use the Pythagorean formula to calculate the distance between two points. In C#:

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

    Why does this work? Have a look at the following diagram and remember that a^2 + b^2 = c^2 holds for right triangles:

    Pythagoras

    0 讨论(0)
  • 2020-12-20 23:08

    Just calculate the square of the distance using Pythagoras' theorem, and compare to the square of the radius:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题