如何将十六进制网格转换为压扁的十六进制网格?

时间:2014-04-02 05:24:52

标签: unity3d unityscript hexagonal-tiles

我有六角网格的这些功能。它们适用于常规十六进制网格。这些函数对于压扁的六角网格有什么作用。通过压扁十六进制网格,我的意思是一个网格,其中每个十六进制都比它高。

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
})

这是我用压扁十六进制网格表示的意思。 hex grid image

以下是转换和舍入功能。

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}
}

1 个答案:

答案 0 :(得分:1)

想出来。 coordinates_to_pixel是Math.sqrt(3)* squish因子。 Pixel_to_coordinates是Math.sqrt(3)/ squish_factor。一个是乘法,另一个是分裂。