Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine If Two Points Are Near

Tags:

c#

.net

math

vb.net

I have the following:

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

I want to return true in the function if the current point is in 25 pixels radius of the old point. Can anyone tell me how to do that?

like image 811
Elmo Avatar asked Oct 23 '12 14:10

Elmo


2 Answers

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

like image 197
Heinzi Avatar answered Sep 24 '22 15:09

Heinzi


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;
}
like image 22
Daniel Fischer Avatar answered Sep 22 '22 15:09

Daniel Fischer