1

I have a hexagon shaped grid of hexagons. I need to find the grid coordinates of a tile that a user clicks on. How can I do this if the code below calculates where the tiles are drawn?

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++;             
            }
        }
    }

This is the coordinate system I use: enter image description here

ShoeLace1291
  • 4,335
  • 12
  • 43
  • 76
  • In your code you use the `Hexagon` class. Look inside it, it likely stores all vertices. If it does, calculationg if a point is inside vertices is pretty strightforward – BackSlash Mar 29 '17 at 11:27

1 Answers1

0

There's not much coding here but geometry at most.
You get hexagon's center xc,yc and radius r (radius equals side length).
To calculate where corners of particular hexagon lie you should:

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

If you use screen coordinates then your y-axis is reverted so you switch signs when calculating y-coordinates.

If you also need to figure out which hexagon was clicked then you will need to calculate distance between mouse click and center of each hexagon. If it's lower than radius of given hexagon - you have your clicked hex and proceed as described above.

zubergu
  • 3,556
  • 3
  • 23
  • 36