我想检查两组坐标是否彼此接近。我看了看 this answer ,建议使用毕达哥拉斯公式计算两点之间的距离。
我比较的两组坐标是鼠标当前位置,和变量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");
}
变量 point
具有点数据类型。
我正在使用 this.PointToClient(Cursor.Position)
而不是 Cursor.Position
因为我想获取相对于表单的坐标,而不是相对于屏幕。但是使用它会给我以下错误:
Cannot convert from
int
toSystem.Drawing.Point
最佳答案
你输入了.X
和 .Y
在错误的一边:首先转换点,然后取其坐标。
另一个问题是 < 50
位置
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");
}
您可能想要提取 this.PointToClient(Cursor.Position)
有 if
更具可读性:
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");
}
关于c# - 比较坐标时无法从 int 转换为 System.Drawing.Point,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59321793/