So basically what i want to do is simple, i have a hex grid and a game object let’s say it’s the player, what i want to do is know on wich cell the player is on based on his world position, this would be easy on a simple grid but on a hex grid its giving me a headach, if anyone can give me an approache to this it would be very much appreciated thank you.
public Vector2 GetHex(Vector3 point)
{
int column;
int row;
// Find out which major row and column we are on:
row = (int)(point.z / 0.87f);
column = (int)(point.x / (radius + radius/2));
// Compute the offset into these row and column:
float dz = point.z - (float)row * 0.87f;
float dx = point.x - (float)column * (radius + radius/2);
// Are we on the left of the hexagon edge, or on the right?
if (((row ^ column) & 1) == 0) {
dz = 0.87f - dz;
}
int right = dz * (radius - radius/2) < 0.87f * (dx - radius/2) ? 1 : 0;
// Now we have all the information we need, just fine-tune row and column.
row += (column ^ row ^ right) & 1;
column += right;
return new Vector2(Mathf.RoundToInt(column), Mathf.RoundToInt(row / 2));
}