蜂窝网格算法

来源:互联网 发布:unity3d小游戏源码 编辑:程序博客网 时间:2024/04/27 22:01

平行状态蜂窝网格

根据网格上来的代码,修改成自己想要的坐标系。


#define CELL_BORDER (40) //六边形边长


#define GRID_WIDTH (CELL_BORDER*1.5f)
#define GRID_HEIGHT (CELL_BORDER*0.8660254f)    // sqr(3)/2=0.8660254
#define TEMP_1 ((GRID_WIDTH*GRID_WIDTH - GRID_HEIGHT*GRID_HEIGHT)/2.f)
#define TEMP_2 ((GRID_WIDTH*GRID_WIDTH + GRID_HEIGHT*GRID_HEIGHT)/2.f)


//2d坐标转网格坐标
void GetCell(int xPos, int yPos, int& cell_x, int& cell_y)
{
cell_x = (int)(xPos / GRID_WIDTH);
float x = xPos - cell_x*GRID_WIDTH;
cell_y = (int)(yPos / (GRID_HEIGHT));
float y = yPos - cell_y*(GRID_HEIGHT);


if((cell_x + cell_y) & 1)
{//奇数
if(x*GRID_WIDTH - y*GRID_HEIGHT > TEMP_1)
cell_x++;
}
else
{
if(x*GRID_WIDTH + y*GRID_HEIGHT > TEMP_2)
cell_x++;
}


cell_y = (int)((cell_y + (1 - (cell_x & 1))) / 2);
}


//网格坐标转2d坐标中心点
void GetCenterPoint(int cell_x, int cell_y, int &xPos, int &yPos)
{
yPos = cell_y * GRID_HEIGHT * 2 + GRID_HEIGHT* (cell_x & 1);
xPos = cell_x * GRID_WIDTH;
}


//2d坐标中心点取六边形的六个端点
void GetCellPoints(int cellx, int celly, int a, POINT *lpPoints)
{
if(lpPoints == NULL) return;
//平
lpPoints[0].x = cellx - a;
lpPoints[0].y = celly;


lpPoints[1].x = cellx - (int)(a * 0.5);
lpPoints[1].y = celly - GRID_HEIGHT;


lpPoints[2].x = cellx + (int)(a * 0.5);
lpPoints[2].y = lpPoints[1].y;


lpPoints[3].x = cellx + a;
lpPoints[3].y = celly;


lpPoints[4].x = lpPoints[2].x;
lpPoints[4].y = celly + GRID_HEIGHT;


lpPoints[5].x = lpPoints[1].x;
lpPoints[5].y = lpPoints[4].y;

}

0 0
原创粉丝点击