我有一个六边形的六边形网格。我需要找到用户单击的图 block 的网格坐标。如果下面的代码计算了绘制图 block 的位置,我该如何做到这一点?
private void CalcHexCoords() {
Point origin = new Point(originX, originY);
double ang30 = Math.toRadians(30);
double xOff = Math.cos(ang30) * (radius + padding);
double yOff = Math.sin(ang30) * (radius + padding);
int half = size / 2;
int i = 0; //total number of tiles
for (int row = 0; row < size; row++) {
int cols = size - Math.abs(row - half);
for (int col = 0; col < cols; col++) {
int xLbl = row < half ? col - row : col - half;
int yLbl = row - half;
int centerX = (int) (origin.x + xOff * (col * 2 + 1 - cols));
int centerY = (int) (origin.y + yOff * (row - half) * 3);
Hexagon hex = new Hexagon(centerX, centerY, radius);
hexagons.add(hex);
int[] coords = new int[]{xLbl, yLbl};
Tile tile = new Tile(rsrc, hex.center, radius, diceSpaces.get(i), coords, i, hex);
tiles.put(coords[0] + "," + coords[1], tile);
i++;
}
}
}
这是我使用的坐标系:
这里没有太多编码,最多只是几何图形。
您将得到六边形的中心 xc,yc 和半径 r(半径等于边长)。
要计算特定六边形的角点所在的位置,您应该:
North corner: xc , yc+r,
South:xc,yc-r,
NE:xc+r, yc+1/2r,
NW:xc-r,yc+1/2r,
SE:xc+r,yc-1/2r
SW:xc-r,yc-1/2r
如果您使用屏幕坐标,那么您的 y 轴将被恢复,以便您在计算 y 坐标时切换符号。
如果您还需要找出单击了哪个六边形,那么您将需要计算鼠标单击与每个六边形中心之间的距离。如果它小于给定六边形的半径 - 您将获得单击的六边形并按照上述说明进行操作。
我是一名优秀的程序员,十分优秀!