15 Sep 2017

Based on this stackexchange question:

Rotation: {{rotation}}

If you need to record both range and direction as part of what a unit is allowed to do, you can make an array of coordinates with each type of action. This allows custom shapes. Here, I made the front area wide, the side areas with a minimum range, and the rear areas with a longer range straight back:

    '0,0': 'center',
    '-1,-1': 'front',
    '0,-1': 'front',
    '1,-1': 'front',
    '2,-1': 'front',
    '0,-2': 'front',
    '1,-2': 'front',
    '2,-2': 'front',
    '-2,0': 'side',
    '2,0': 'side',
    '-2,1': 'rear',
    '-1,1': 'rear',
    '0,1': 'rear',
    '1,1': 'rear',
    '-1,2': 'rear',

These coordinates are based on the unit being in the center, facing north. But what about other locations and orientations? You can transform these coordinates. First rotate the coordinates to match the direction the unit is facing. I used this function:

function hex_rotate(hex, rotation) {
    while (rotation < 0) {
        hex = hex_rotate_left(hex);
        rotation++;
    }
    while (rotation > 0) {
        hex = hex_rotate_right(hex);
        rotation--;
    }
    return hex;
}

(The hex_rotate_left and hex_rotate_right functions are from my hex implementation page, based on the ideas here.)

After rotating, transform by translating to the unit’s location. With cube or axial coordinates, this is simple; you can add the coordinates together:

function hex_add(a, b) {
    return Hex(a.q + b.q, a.r + b.r, a.s + b.s);
}

I try to solve these kinds of problems by breaking them into smaller ones. Hex labeling (with a table), hex rotation, and hex translation (add) are simpler problems to solve.