Taersious
Taersious

Reputation: 779

Canvas Translate Routine to Move Along a Hexagonal Path

I have a script in place and running that allows me to move an image along a path, but my path goes off track (on hexagon map) after about 6 moves.

I know there is a function to handle this, but right now I am unable to find what to do. Currently, I am using a set float value for the x and y moves that are anything other than a move up or down (0 degrees and 180 degrees), which are a set integer value.

Here's my psuedo-code:

function doTranslate(deg, goX, goY) {
   clearCanvas();
   var context = surface.getContext('2d');
   context.save();
   context.translate(goX,goY);
   context.rotate(DegToRads(deg));
   context.drawImage(gamePiece, -10, -10);
   context.restore();
}

Again, this all works, but my calculated values for goX and goY are global variables that get updated based on the direction we are moving. Right now, I am using a float of 18.3 for my x move, and 9.8 for my y move, and a int value of 21 for my straight up or down moves.

I remember from college (only vaguely) that I need to do some square roots and PI operations in there somewhere, but right now I am just adding and subtracting the static values for each move.

Has anyone already solved this?

Upvotes: 2

Views: 415

Answers (1)

enderskill
enderskill

Reputation: 7684

To move something on a hexagonal grid it would have to follow these fundamental units.

position graph

To put it in semi-pseudocode:

s = 10.0; //Scale (how far you want the object to move)

//Move right
goTo(2*s,0*s)

//Move up-right
goTo(1*s,Math.sqrt(3)*s)

//Move up-left
goTo(-1*s,Math.sqrt(3)*s)

//Move left
goTo(-2*s,0*s)

//Move down-left
goTo(-1*s,-Math.sqrt(3)*s)

//Move down-right
goTo(1*s,-Math.sqrt(3)*s)

Now, if you want the hexagon to be oriented up and down instead of left and right, use this code:

s = 10.0; //Scale (how far you want the object to move)

//Move up
goTo(0*s,2*s)

//Move up-left
goTo(-Math.sqrt(3)*s,1*s)

//Move down-left
goTo(-Math.sqrt(3)*s,-1*s)

//Move down
goTo(0*s,-2*s)

//Move down-right
goTo(Math.sqrt(3)*s,-1*s)

//Move up-right
goTo(Math.sqrt(3)*s,1*s)

Hope it helps!

Upvotes: 3

Related Questions