1
  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);
    }
  }

I'm trying to script something together to automatically build a grid of Hexagons. Hexagons are of arbitrary size u, and Hexagon'0' should be in the centre of a window x by y with sequential ones added in rings around it.

In theory, I think, my maths should be sound, but something is going drastically wrong somewhere, because it does this instead.

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

They just go in a diagonal downwards line. Apologies for the low-def image!

Would anyone be able to help me fix my code and/or point out the glaring failure in mathematics? Will provide the entire program if needed!

Java42
  • 7,628
  • 1
  • 32
  • 50
Panda
  • 11
  • 2
  • A compilable version of the code always helps others to help you out. [SSCE](http://sscce.org/) – StoopidDonut Jan 25 '14 at 14:13
  • A grid is two dimensional, and requires two for loops (you could do it with one with some undecipherable math). One for loop should move the x-coordinate, the other should move the y-coordinate of the center of the hexagon. – Teepeemm Jan 25 '14 at 15:02

1 Answers1

1

From the code, all the centers of your hexagon indeed lie on the line C(t) = (x/2+3*u*t*c, y/2+u*t*s). In your outer loop, you need to generate hexagon centers coordinates that actually lie on a spiral.

user3146587
  • 4,250
  • 1
  • 16
  • 25