Problem of creation of hex map
I have a code which builds a hex map:
int diamater = 32;
int grid_x_size = 19;
int grid_y_size = 5;
for (int x=0; x<grid_x_size; x++) {
for (int y=0; y<grid_y_size; y++) {
int x_position = diamater*x+(y%2)*开发者_JAVA百科diamater/2;
int y_position = diamater*y;
add(new ImageSprite(image, x_position, y_position, diamater, diamater));
}
}
It looks here so: Screnshot
Why between rows there is a distance? And balls lie not densely?
Thanks!
You are trying to produce a hexagonal packing, not a square packing.
The vertical distance between the centers of the circles should be less than the diameter because the tops of the second row fill the holes between the bottoms of the first row, causing the bounding boxes of the first two rows to overlap slightly. Note that in the first picture there are only five rows of circles, but in the second there are six rows, despite that the second packing doesn't take up much more vertical space.
The actual height difference between the rows is the height of an equilateral triangle with sides equal to the diameter of your circle, which can be calculated using the Pythagorean Theorem, for example.
Try y_position = sqrt(3)/2 * diameter * y
.
The centers of three adjacent circles form an equilateral triangle, with the edge length being the diameter (32 in your example). So, the distance between the center of the bottom circle and the line connecting the centers of the top circles would be sqrt(3)/2 times that value (27.7 in your example). So, int y_position = 27.7 * y;
the y_pos calculation is your bug:
This should fix it: int y_position = sin(pi / 3) * diamater * y;
You might want to cache sin(pi/3) for performance.
精彩评论