那么如何从特定距离获得点的x,y坐标?
所以
public static Location2D DistanceToXY(Location2D current, Directions dir, int steps) {
ushort x = current.X;
ushort y = current.Y;
for (int i = 0; i < steps; i++) {
switch (dir) {
case Directions.North:
y--;
break;
case Directions.South:
y++;
break;
case Directions.East:
x++;
break;
case Directions.West:
x--;
break;
case Directions.NorthWest:
x--;
y--;
break;
case Directions.SouthWest:
x--;
y++;
break;
case Directions.NorthEast:
x++;
y--;
break;
case Directions.SouthEast:
x++;
x++;
break;
}
}
return new Location2D(x, y);
}
这里做的是对的吗?
答案 0 :(得分:0)
我假设您正在寻找一般解决方案。正如其他人指出的那样,你需要一个方向作为缺失的输入。您将基本上使用方向和幅度(在这种情况下为10)并将这些极坐标转换为笛卡尔坐标。然后你将坐标加在一起X + Xoffset = Xnew,Y + Yoffset = Ynew。
转换的详细信息如下: http://www.mathsisfun.com/polar-cartesian-coordinates.html
编辑:发布代码后,答案是否定的。 NorthWest,SouthWest,NorthEast,SouthEast的案例不正确。在这些情况下,您移动1.41(aprox)像素。你不应该尝试逐步解决难题。使用极坐标数学并对总偏移求和,然后舍入到最接近的整数。
下面是解决方案的简化伪代码mod:
public static Location2D DistanceToXY(Location2D current, Directions dir, int steps) {
ushort x = current.X;
ushort y = current.Y;
switch (dir) {
case Directions.North:
y=y+steps;
break;
case Directions.South:
y=y-steps;
break;
case Directions.East:
x=x+steps;
break;
case Directions.West:
x=x-steps;
break;
case Directions.NorthWest:
float sqrt2 = 2 ^ 0.5
x=x+int((sqrt2 * steps) + 0.5);
y=y-int((sqrt2 * steps) + 0.5);
break;
case Directions.SouthWest:
x=x-int((sqrt2 * steps) + 0.5);
y=y-int((sqrt2 * steps) + 0.5);
break;
case Directions.NorthEast:
x=x+int((sqrt2 * steps) + 0.5);
y=y+int((sqrt2 * steps) + 0.5);
break;
case Directions.SouthEast:
x=x-int((sqrt2 * steps) + 0.5);
y=y+int((sqrt2 * steps) + 0.5);
break;
}
return new Location2D(x, y);
}