Sunday, July 24, 2016

c# - How can I implement hexagonal tilemap picking in XNA?


I have a hexagon tiled map in which I need to check when a hexagon is clicked. The hexagons aren't actually touching, rather they have a slight gap in between each of them.


Does anyone know how could I go about checking whether a hexagon is clicked without over complicating the whole thing?



Answer



Take a look to this picture


hexagonal decomposition


As you can see there is a relatively intuitive way to map x,y rectangular coordinate system to the hexagonal one.


We may talk about "rect" irregular hexagons ie hexagons inscribed in ellipses or hexagons obtained from regular hexagons scaled in both directions disproportionately (no rotations-shearings).


A rect hexagon can be defined by the height and width of the circumscribing rectangle plus the width of the inscribing one. (W,w,h)



inscribing/circumscribing rectangles


The easiest way to find out the hexagonal index is to partitionate the space as follow:


space partition


The rectangle width is w + (W - w)/2 = (w + W)/2, its height is h/2; the width of the green rectangle is (W-w)/2. Is easy to find out where in which rectangle the point falls:


enter image description here


u and v are the reminder coordinates that indicates where the point is whithin the i,j rectangle: Using w we can say if we are in the green area (u < (W-w)/2) or not.


if it is the case we are in the green area we need to know if we are in the upper or lower half of the hexagon: we are in the upper half if i and j are both even or both odd; we are in the lower half otherwise.


In both cases it is usefull to trasform u and v so they vary between 0 and 1:


enter image description here


if we are in the lower half and v < u



or


if we are in the upper half and (1-v) > u


then we decrement i by one


Now we simply have to decrement j by one if i is odd to see that i is the horizontal hexagon index (column) and the integer part of j/2 is the vertical hexagon index (row)


enter image description here


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...