Samual Lewis
Samual Lewis

Reputation: 3

Java LWJGL - Creating a Grid of Squares

Picture
(The colored squares are just positions that have been added to an array to be drawn)
I am having problems creating a grid of squares in Java. As you can see in the picture, it appears as if the squares are being placed in the right position, but they are progressively getting smaller in x and in y as x and y grows. I have been trying to find the right algorithm for this for a while now and I am having problems.

public void draw() {
    setColor(material);
    glBegin(GL_QUADS);
        glVertex2i(x+(SIZE*(x-1)), y+(SIZE*(y-1))); //top-left vertex
        glVertex2i(SIZEx, y+(SIZE(y-1)));         //top-right vertex
        glVertex2i(SIZEx, SIZEy);                 //bottom-left vertex
        glVertex2i(x+(SIZE*(x-1)), SIZE*y);         //bottom-right vertex
    glEnd();
}
SIZE is set to 32.

Upvotes: 0

Views: 1314

Answers (1)

ds-bos-msk
ds-bos-msk

Reputation: 772

The problem here is that you are adding "+x" and "+y" in several places this is why the squares are changing in their size as x and y progresses. If you wish to write to make squares with some small distance in between them, you could try something like this, say SIZE=32 and PADDING_HALF=1, then something like this should work (this way the squares should be 30x30 with a padding of 2 between each):

public void draw() {
    setColor(material);
    glBegin(GL_QUADS);
        glVertex2i(SIZE*(x-1) + PADDING_HALF, SIZE*y     - PADDING_HALF); //top-left vertex
        glVertex2i(SIZE*x     - PADDING_HALF, SIZE*y     - PADDING_HALF); //top-right vertex
        glVertex2i(SIZE*(x-1) + PADDING_HALF, SIZE*(y-1) + PADDING_HALF); //bottom-left vertex
        glVertex2i(SIZE*x     - PADDING_HALF, SIZE*(y-1) + PADDING_HALF); //bottom-right vertex
    glEnd();
}

Also bear in mind that in OpenGL the y-coordinate isn't inverted.

Upvotes: 1

Related Questions