Determine if two points are

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 to the function if the current point is within a radius of 25 pixels from the old point. Can someone tell me how to do this?

+4
source share
4 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 it work? Look at the following diagram and remember that a^2 + b^2 = c^2 holds for right triangles:

Pythagoras

+15
source

Just calculate the square of the distance using the Pythagorean theorem, and compare with 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; } 
+4
source

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); 
+2
source

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

0
source

Source: https://habr.com/ru/post/1441574/


All Articles