While you may think rectangles are only shapes that can be used in tiles, it is not true. You can use other shapes too, for example triangles. In this chapter we will look how to use hexagonal tiles. Hexagonal grid is widely used in strategic board games as it allows 3 directions of movement while keeping the distance in each direction equal. Diagonal movement in square based grid is not good because the distance in diagonal is different then distance in horisontal/vertical.
A regular hexagon has six edges and looks like this:
Important variables to remember here are the height and size which we will be using to place tiles correctly on the stage. Size represents the length of each side. Lets look how hex tiles will be layed out on the stage:
Vertically each next tile is placed down by the value of tiles height.
Plus every other row is moved additionally down by half of the tiles height. We can use "modulo" operator to pick every other row. x%2 will return 0 if x is 0, 2, 4 (those are columns A, C and E) and it returns 1 if x is 1, 3, 5 (columns B, D, F). So final equation to find y coordinate is:
Horisontally each tile is placed right by the value:
We obviously need to find somehow value of size (s) to place the hexagonal tiles. Size can be found from the height like this:
and final equations to place hex tiles become:
s=h/Math.cos(30*Math.PI/180)/2; tile._x=x*s*1.5; tile._y=y*h+(x%2)*h/2;
Sometimes we need to calulate x and y from the screen coordinates for example to find out over which tile the mouse cursor is placed:
Here is example movie, where hex tiles are placed on screen and you can move mouse to see which tile is under it:
Neighbours for hextiles
With rectangular tiles it was very easy to find its neighbours, tile left was x-1, right was x+1, down y+1 and up y-1. With hexagonal tiles the way to find its neighbours depends on the column where current tile is. Still, tile down is simply y+1 and tile up is y-1. Now tiles up-left and down-left have x-1, also tiles up-rigth and down-right have x+1, but we have to check their row too.
If current tiles is in columns B, D, F, then its neighbours are:
ul.y=y; dl.y=y+1; ur.y=y; dr.y=y+1;
If current tiles is in columns A, C, E, then its neighbours are:
ul.y=y-1; dl.y=y; ur.y=y-1; dr.y=y;
Like before you can use modulo2 to avoid writing different code for 2 columns:
//down dx=x; dy=y+1; //up ux=x; uy=y-1; //up-left col=x%2; col1=(x+1)%2; ulx=x-1; uly=y-col1; //down left dlx=x-1; dly=y+col; //up-rigth urx=x+1; ury=y-col1; //down-right drx=x+1; dry=y+col;
You can download the source fla with all the code and movie set up here.