2014-01-25 36 views
0
public void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 
    for (int n = 0; n < 13; n++) 
    { 
     double hexCentX = x/2+(3*u*n*Math.cos(Math.PI/3)); 
     double hexCentY = y/2+(u*n*Math.sin(Math.PI/3)); 
     Polygon sn = new Polygon(); 
     for (int i = 0; i < 6; i++) 
      sn.addPoint((int) (hexCentX + u * Math.cos(i * Math.PI/3)), 
       (int) (hexCentY + u * Math.sin(i * Math.PI/3))); 
     g.drawPolygon(sn); 
     g.drawString(Integer.toString(n), (int)hexCentX, (int)hexCentY); 
    } 
    } 

我想腳本一起自動構建一個六邊形網格。 六邊形是任意大小的ü,和Hexagon'0' 應該是在一個窗口X的中心通過ý與它周圍的環加入順序的。在Java中自動生成一個六角形網格

從理論上講,我認爲,我的數學應該是健全的,但是某些地方會出現大幅度的錯誤,因爲它是這樣做的。

https://www.dropbox.com/s/suj282lnkmxn0g1/hexagons.bmp

他們剛進去的對角線向下行。低分辨率圖像道歉!

任何人都可以幫助我修復我的代碼和/或指出數學中明顯的失敗嗎?如果需要,將提供整個程序!

+0

代碼的編譯版本總是幫助別人來幫助你。 [SSCE](http://sscce.org/) – PopoFibo

+0

一個網格是二維的,並且需要兩個for循環(你可以用一個具有一些不可破譯的數學來做)。一個for循環應該移動x座標,另一個應該移動六邊形中心的y座標。 – Teepeemm

回答

1

從代碼中,你六邊形的所有中心確實位於線C(t) = (x/2+3*u*t*c, y/2+u*t*s)。在你的外部循環中,你需要生成實際位於螺旋上的六邊形中心座標。

0

抱歉其在c#但算法是相同的...

下面的方法將在一個大的六角形圖案創建不吉利的東西的2D陣列。

private void generateMap(int size) { 
// size is number of rings not counting center so array length is... 
mapHexs = new Hex[(size*2)+1,(size*2)+1]; 
// offsets to traverse (sw,w,nw,ne,e,se) from a tile 
int[,] offsetsOdd = new int[,] {{-1,-1},{-1,0},{-1,1},{0,1},{1,0},{0,-1}}; 
int[,] offsetsEven = new int[,] {{0,-1},{-1,0},{0,1},{1,1},{1,0},{1,-1}}; 

//start in the center 
int posX = size; 
int posY = size; 

// each ring 
for (int ring = 1; ring <= size; ring++) { 
    // at the start of a ring step out one 
    posX++; 
    // each side 
    for(int side = 0; side < 6; side++) { 
     // tiles per side 
     for(int idx = 0; idx < ring; idx++) { 
      // odd or even line 
      if(posY % 2 == 0) { 
       posX += offsetsEven[side,0]; 
       posY += offsetsEven[side,1]; 
      } else { 
       posX += offsetsOdd[side,0]; 
       posY += offsetsOdd[side,1]; 
      } 
      mapHexs[posX,posY] = new Hex(); 
     } 
    } 
} 

然後做出這樣的事情來繪製...

public void drawHexs() { 
    // step through the hex array and add hexs as needed 
    for (int y = 0; y < mapHexs.GetLength(1); y++) { 
     for (int x = 0; x < mapHexs.GetLength(0); x++) { 
      // is there a hex here? 
      if(mapHexs[x,y] != null) { 
       // calc X and y, note : HEX_HEIGHT_OFFSET is not the image hight but the 
       // hight from the bottom corner to the sholder of the hex (missing the top 1/4) 
       int posX = x * HEX_WIDTH; 
       int posY = y * HEX_HEIGHT_OFFSET 
       // offset by 1/2 a hex on even lines 
       if(position.y % 2 == 0) 
        x = x + HEX_WIDTH/2f; 
       createHex(posX,PosY); 
      } 
     } 
    } 
}