3

I am using flat topped hexagonal grid (following the manual listed here http://www.redblobgames.com/grids/hexagons/).

enter image description here

I need to convert my cube coordinates into pixel coordinates. I have read Hexagonal Grid Coordinates To Pixel Coordinates but the solution listed there requires some modifications to work with flat topped grid. The logic must be similar to the one described in the question linked above but I can't work it out.

Definitely in case of flat top hexes x-coordinate may be used as x pixel coordinate. Thus calculating X pixel coordinate from cube coordinates is relatively easy. Assuming that $this->hexSize is total width of hex and $cubeCoordinate is an array of x,y,z coordinates the x-pixel coordinate will be:

$pixelCoordinate['x'] = $this->hexSize * $cubeCoordinate['x'] * 3/4;

I can't work out though how to calculate y pixel coordinate. The height between adjacent hexes should be deficiently equal to $this->hexSize. But how to calculate offset based on cube coordinates?

Community
  • 1
  • 1
Abdel5
  • 1,112
  • 3
  • 16
  • 39
  • I'm using a flat top grid like this, and I'm trying to determine where to position a square image of a highlighted/selected hex such that displaying that image at that location visually highlights/selects the correct hex. So I'm going from mouse x,y to a viewport x,y for the square image of a hex. It seems that both vx and vy will depend on both mx and my; the solution will have to correctly determine which side of those diagonal lines the mouse is on. – Shavais Jan 02 '19 at 18:02

1 Answers1

4

I have worked it out, inserting diffrent variables into the equasions listed here Hexagonal Grid Coordinates To Pixel Coordinates.

Finally it occurred that the cube coordinates in flat top hexagonal grid may be calculated using the following code:

   /* 
* Changes cube coordinates into offset one
        */
        public function coordinates_CubetoOffset($cube)
        {

            $return['x'] = $this->hexSize * $cube['x'] * 3/4;
            $return['y'] = sqrt(3)/2 * $this->hexSize * ($cube['x']/2 + $cube['y']);


            return $return;
        }
Community
  • 1
  • 1
Abdel5
  • 1,112
  • 3
  • 16
  • 39
  • Thank you for this post.. I'm following the same guide and running into the same issue with my flat top grid. Are you using negative coordinates (0,0 at center) and how do you handle that? Just add half the grid size to x and y? – Ryan Langton Feb 24 '17 at 14:59