开发者

Count Hexagons inside a Rectangle?

I'm looking for an algorithm to count hexagons that fall within a rectangular area, whether cropped or not.

I know the following:

rectWidth = 1280;
rectHeight = 720;
hexRadius = 50; // middle to corner
hexHeight = hexRadius * 2;
hexShortSpan = hexRadius * 0.5;
hexLongSpan = cos(radians(30)) * hexRadius;
hexWidth = hexLongSpan * 2;
hexSide = hexRadius + hexShortSpan; // this is not a side but side + shortSpan for horizontal rows

Can't figure out the mod op to get the right result.

float A = rectWidth / hexWidth;
float B = rectHeigh开发者_如何学Got / hexSide;
float hexCount = A * B +????;
// etc. etc. not sure about the rest...

Rob

Here's an image…

http://moggach.com/media/img/hexGrid.jpg


Calculate the area of a hexagon, and divide the area of the rectangle with the area of the hexagon.

The area of the hexagon is

a*a * (3 * sqrt(3)) / 2

where a is the length of a side of the hexagon.


Hint: count numbers of hex corners on one side. E.g. count all hex right corners (X's): ...

With top left corner in the middle of first hexagon, situation is less general. It can be solved with counting:

  • how many hexes are in first row (split by upper border)
  • how many hexes are in second row (just below first one)
  • how many rows are of first row type (every second from first row)
  • how many rows are of second row type (every second from second row)

This is python version of code:

from math import ceil, cos, sqrt
rectWidth = 1280
rectHeight = 720
hexRadius = 50
hexHeight = hexRadius * 2
hexHalfHeight = hexRadius/2
hexWidth = hexRadius * sqrt(3)

# First one is corner, ceil() calculates others in row
num_in_first_row = 1 + ceil( ( rectWidth - hexWidth ) /hexWidth )
num_in_second_row = ceil( rectWidth / hexWidth )

# First one is corner, ceil() starts from upper point of next hex on left border
num_of_first_rows = 1 + ceil( ( rectHeight - 2 * hexRadius ) / ( hexHeight + hexRadius ) )
# Starts from upper point of first hex in second row. Coords (hexWidth/2., hexHalfHeight)
num_of_second_rows = ceil( ( rectHeight - hexHalfHeight ) / ( hexHeight + hexRadius ) )

num = num_in_first_row * num_of_first_rows + num_in_second_row * num_of_second_rows
print num
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜