gpt4 book ai didi

java - 如何在Java中通过像素点获取六边形图 block 的网格坐标?

转载 作者:太空宇宙 更新时间:2023-11-04 11:37:44 24 4
gpt4 key购买 nike

我有一个六边形的六边形网格。我需要找到用户单击的图 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++;
}
}
}

这是我使用的坐标系: enter image description here

最佳答案

这里没有太多编码,最多只是几何图形。
您将得到六边形的中心 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 坐标时切换符号。

如果您还需要找出单击了哪个六边形,那么您将需要计算鼠标单击与每个六边形中心之间的距离。如果它小于给定六边形的半径 - 您将获得单击的六边形并按照上述说明进行操作。

关于java - 如何在Java中通过像素点获取六边形图 block 的网格坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43092161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com