Skip to main content
2 of 2
replaced http://gamedev.stackexchange.com/ with https://gamedev.stackexchange.com/

As Martin Sojka notes, rotations are simpler if you convert to a different coordinate system, perform the rotation, then convert back.

I use a different coordinate system than Martin does, labeled x,y,z. There's no wobble in this system, and it's useful for lots of hex algorithms. In this system you can rotate the hex around 0,0,0 by “rotating” the coordinates and flipping their signs: x,y,z turns into -y,-z,-x one way and -z,-x,-y the other way. I have a diagram on this page.

(I'm sorry about x/y/z vs X/Y but I use x/y/z on my site and you use X/Y in your code so in this answer the case matters! So I'm going to use xx,yy,zz as the variable names below to try to make it easier to distinguish.)

Convert your X,Y coordinates to the x,y,z format:

xx = X - (Y - Y&1) / 2 zz = Y yy = -xx - zz 

Perform a rotation by 60° one way or the other:

xx, yy, zz = -zz, -xx, -yy # OR xx, yy, zz = -yy, -zz, -xx 

Convert the x,y,z back to your X,Y:

X = xx + (zz - zz&1) / 2 Y = zz 

For example, if you start with (X=-2, Y=1) and want to rotate 60° right, you'd convert:

xx = -2 - (1 - 1&1) / 2 = -2 zz = 1 yy = 2-1 = 1 

then rotate -2,1,1 60° right with:

xx, yy, zz = -zz, -xx, -yy = -1, 2, -1 

as you see here:

Hex rotation example for -2,1,1

then convert -1,2,-1 back:

X = -1 + (-1 - -1&1) / 2 = -2 Y = -1 

So (X=-2, Y=1) rotates 60° right into (X=-2, Y=-1).

amitp
  • 6.1k
  • 3
  • 29
  • 43