Question

I have these functions for a hex grid. They work great for a regular hex grid. What would these functions be for a squished hex grid. By squished hex grid I mean a grid where each hex is wider than it is tall.

coordinates_to_pixel = function(x, y) {
    var pixel_x = s_hex_size * 3/2 * x
    var pixel_y = s_hex_size * Math.sqrt(3) * (y + x/2)
    return { x: pixel_x, y: pixel_y }
}

pixel_to_coordinates = function(x, y) {
    var q = 2/3 * x / s_hex_size
    var r = (1/3 * Math.sqrt(3) * y - 1/3 * x) / s_hex_size
    var cube = convert_axial_to_cube_coordinates(q,r)
    var round = round_cube_coordinates(cube.x, cube.y, cube.z)
    var axial = convert_cube_to_axial_coordinates(round.x, round.y, round.z)
    return { x:axial.x, y:axial.y }
}

hex_points = function(x, y) {
    var pixel = coordinates_to_pixel(x,y)

    var points = ''
    for (var i = 0; i < 6; i++) {
        var angle = 2 * Math.PI / 6 * i

        var point_x = (hex_size * Math.cos(angle)) + pixel.x + canvas_width/2
        var point_y = (hex_size * Math.sin(angle)) + pixel.y + canvas_height/2

        if (i != 0) { points = points + ' '; }
        points = points + point_x.toString() + ',' + point_y.toString()
    }
    return points
})

Here's an image of what I mean by squished hex grid. hex grid image

Here are the conversion and rounding functions.

convert_axial_to_cube_coordinates = function(q,r) {
    return {
        x: q,
        y: -1 * q - r,
        z: r
    }
}


convert_cube_to_axial_coordinates = function(x,y,z) {
    return {x: x, y: z}
}


round_cube_coordinates = function(x,y,z) {
    var rx = Math.round(x)
    var ry = Math.round(y)
    var rz = Math.round(z)

    var x_diff = Math.abs(rx - x)
    var y_diff = Math.abs(ry - y)
    var z_diff = Math.abs(rz - z)

    if (x_diff > y_diff && x_diff > z_diff) {
        rx = -1 * ry - rz
    } else if (y_diff > z_diff) {
        ry = -1 * rx - rz
    } else {
        rz = -1 * rx - ry
    }

    return {x: rx, y: ry, z: rz}
}
Was it helpful?

Solution

Figured it out. coordinates_to_pixel is Math.sqrt(3) * squish factor. Pixel_to_coordinates is Math.sqrt(3) / squish_factor. One is multiply the other is divide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top