Converting a point to a hexagon coordinate

geometry

Here is a link to a graphing calculator to help you visualize what I'm talking about (I made it): https://www.desmos.com/calculator/ccxnopqqkr

Slide Hq and Hr to change the coordinates of the Red Hexagon (Axial coordinates, not Cartesian).

My question is, what formula would convert that black point (or any point in space) to the axial coordinates of the hexagon it falls into? Note, these are not for regular hexagons. If it falls directly on the border between two hexagons, I need it to consistently push (round) in the same direction every time, so that it I can be sure which hex a point will convert to.

The reason I need this is for a game I'm making (A simple board game). It's in an isometric view with a hexagon game grid. The reason the hexagon on that link is scaled down vertically is to match the hexagons in the game. It has the exact same coordinates (including the origin of the hexagon tile being the top-left).

Best Answer

A formula will not be able to deal directly with the edge cases. To convert from $(X,Y)$ to $(H_q,H_r)$ you will need an algorithm. To begin with, imagine vertical lines draw through the top left points of the hexagons. This divides the grid into columns, and you need to know which column the point is in. This is simply $\lfloor\frac{x}{18}\rfloor$. We'll call this value $a$. We then divide that column into cells using the horizontal lines of the hexagons in that column so that each cell is an $18\times14$ rectangle with its top left corner concurrent with that of a hexagon, then find a value $b$ for the cell containing the given point.

When $a$ is even we calculate $b=\lfloor\frac{-y}{14}\rfloor$, and when $a$ is odd $b=\lfloor\frac{-y-7}{14}\rfloor$.

Using these values we find $H_r=b-\lfloor\frac{a}{2}\rfloor$ and $H_q=H_r+a$. Also use these values to find the $(x,y)$ values for the top left corner $P$ of the cell.

When $a$ is even $P_{x,y}=(18a,-14b)$, when $a$ is odd $P_{x,y}=(18a,-14b-7)$.

Now check the location of the given point within the cell to see if it falls in one of the corner regions.

First let $T_x=X-P_x-11$. If this value $T_x\le0$ then the point is in the main region and our values for $H_q$ and $H_r$ are correct. Otherwise, let $T_y=P_y-Y$.

Finally, if $T_y<7$ and $T_x>T_y$ we need subtract $1$ from $H_r$, or if $T_y>7$ and $T_x>14-T_y$ we need to add $1$ to $H_q$.

C code reference (tested and confirmed):

a=floor(x/18);
if(((int)a%2)==0){
    b=floor(-y/14);
    px=18*a;
    py=-14*b;
}else{
    b=floor((-y-7)/14);
    px=18*a;
    py=-14*b-7;
}
hr=b-floor(a/2);
hq=hr+a;
tx=x-px-11;
if(tx>0){
    ty=py-y;
    if((ty<7)&&(tx>ty))hr-=1;
    if((ty>7)&&(tx>14-ty))hq+=1;
}
Related Question