I want to check if two sets of coordinates are close to each other. I had a look at this answer, which suggested using the Pythagorean formula to calculate the distance between two points.
The two sets of coordinates I'm comparing is the current position of the mouse, and preset coordinates under the variable point
if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position.X), 2) + Math.Pow(point.Y - this.PointToClient(Cursor.Position.Y), 2) < 50))
{
Console.WriteLine("Distance between the points is less than 50");
}
The variable point
has the point data type.
I am using this.PointToClient(Cursor.Position)
instead of Cursor.Position
because I want to get the coordinates relative to the form, instead of relative to the screen. However using this gives me the following error:
Cannot convert from
int
toSystem.Drawing.Point
You've put .X
and .Y
at the wrong side: first convert the point, then take its coordinate.
Another issue is < 50
position
if(Math.Sqrt(Math.Pow(point.X - this.PointToClient(Cursor.Position).X, 2) +
Math.Pow(point.Y - this.PointToClient(Cursor.Position).Y, 2)) < 50)
{
Console.WriteLine("Distance between the points is less than 50");
}
You may want to extract this.PointToClient(Cursor.Position)
to have if
more readable:
var cursor = PointToClient(Cursor.Position);
if(Math.Sqrt(Math.Pow(point.X - cursor.X, 2) +
Math.Pow(point.Y - cursor.Y, 2)) < 50)
{
Console.WriteLine("Distance between the points is less than 50");
}