使用OpenGL制作一个2D的六边形棋盘,形状为菱形。

3

我正在为一个六角棋盘游戏制作GUI界面。这个游戏有121个六边形,在一个11x11的菱形中。我已经画出了一个11x11的正方形棋盘。如何将坐标转换为绘制菱形的六边形?以下是每一帧绘制棋盘的代码片段。

    void draw_Board(HexBoard* h) {
    glPushMatrix();
    glTranslatef(1.5f, 1.5f, 0.0f);
    for (auto iter = h->drawList.begin(); iter != h->drawList.end(); ++iter) {
        pointRef t = *iter;
        colorRef c;
        float scale_factor = h->get_scale_factor();
        if (t.player == 0) {
            c.red = 1;
            c.green = 1;
            c.blue = 1;
        }
        else if (t.player == 1) {
            c.red = 1;
            c.green = 0;
            c.blue = 0;
        }
        else if (t.player == 2) {
            c.red = 0;
            c.green = 0;
            c.blue = 1;
        }

        int x_increment = 2;
        int y_increment = 2;

        glPushMatrix();
        //cout << t.x_pos << " " << t.y_pos << endl;
        //cout << c.red << " " << c.green << " " << c.blue << endl;
        glTranslatef(t.x_pos * 2 , t.y_pos * 2, 0);
        draw_Hex(c, scale_factor);
        glPopMatrix();

    }
    glPopMatrix();
}

这是我的棋盘外观: http://imgur.com/criFeDM 目标形状如下: http://upload.wikimedia.org/wikipedia/commons/3/38/Hex-board-11x11-%282%29.jpg

1
我推荐http://www.redblobgames.com/grids/hexagons/作为一个权威指南。 - starmole
1个回答

2
您需要掌握六边形背后的基本三角学知识。如您所见,有两个有效的角度,即30度和60度。我假设您没有获取六边形点本身的问题,因此请专注于网格中的i、j步骤:
- i步长为2*dx,即x轴上的2.0*r*cos(30deg) - j步长改变了x和y,分别为dx在x轴和2.0*dx*sin(60deg)在y轴
现在只需通过网格创建循环并计算每个六边形的起始点...这是10x10网格的结果:
此处是C++源代码:
//---------------------------------------------------------------------------
#include <math.h>
const float hexagon_r=0.2;
const float hexagon_dx=hexagon_r*cos(30.0*M_PI/180.0);
const float hexagon_dy=hexagon_r*sin(30.0*M_PI/180.0);
const float hexagon_gx=2.0*hexagon_dx;
const float hexagon_gy=2.0*hexagon_dx*sin(60.0*M_PI/180.0);
void draw_hexagon(float x,float y,float z)
    {
    glBegin(GL_LINE_LOOP);
    glVertex3f(x-hexagon_dx,y-hexagon_dy,z);
    glVertex3f(x-hexagon_dx,y+hexagon_dy,z);
    glVertex3f(x           ,y+hexagon_r ,z);
    glVertex3f(x+hexagon_dx,y+hexagon_dy,z);
    glVertex3f(x+hexagon_dx,y-hexagon_dy,z);
    glVertex3f(x           ,y-hexagon_r ,z);
    glEnd();
    }
//---------------------------------------------------------------------------
void draw_hexagon_grid(float x,float y,float z,int ni,int nj)
    {
    int i,j; float x0;
    x-=float(ni-1)*hexagon_gx*0.5; // just shift x,y to start position (i=0,j=0)
    x-=float(nj-1)*hexagon_dx*0.5;
    y-=float(nj-1)*hexagon_gy*0.5;
    for (x0=x,j=0;j<nj;j++,x0+=hexagon_dx,x=x0,y+=hexagon_gy)
     for (i=0;i<ni;i++,x+=hexagon_gx)
      draw_hexagon(x,y,z);
    }
//---------------------------------------------------------------------------

使用方法很简单:draw_hexagon_grid(0.0,0.0,-7.0,10,10);
  • x,y,z 是网格的中心点(因为我有3D视图,所以我将z=-7放在相机前面)
  • ni,njxy轴上的网格大小

你可以忽略z轴...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接