PDA

View Full Version : Shape in freeGLUT not drawing correctly



salarc
12-24-2016, 12:28 PM
Hello! I am having problems with shape drawing in freeGLUT C++.
I have been trying to draw a square which moves based on user input on a grid, which looks something like this:
2310

The grid size is based on user input, so i have to use variables for drawing the grid.
I've been trying to make a system in which i create an enum:

enum Direction {
UP,
DOWN,
LEFT,
RIGHT,
NONE
};

Then create a method called
drawCursor(float r, float g, float b, Direction translateDir, int bound, int sz)
and then translate, using glTranslatef() depending on the translateDir using a switch() and drawing the square always in the top left corner (which then gets translated by glTranslatef())

My code looks like this:

void drawCursor(float r, float g, float b, Direction translationDir, int bound, int sz) {
glColor3f(r, g, b);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
switch (translationDir) {
case Direction::UP:
glTranslatef(0, (bound * 2) / sz - 0.002f, 0);
break;
case Direction::DOWN:
glTranslatef(0, (-bound * 2) / sz - 0.002f, 0);
break;
case Direction::LEFT:
glTranslatef((-bound * 2) / sz - 0.002f, 0, 0);
break;
case Direction::RIGHT:
glTranslatef((bound * 2) / sz - 0.002f, 0, 0);
break;
case Direction::NONE:
break;
}
glBegin(GL_POLYGON);
//top left
glVertex3f(-bound + 0.01f, bound - 0.01f, -5.0f);
//top right
glVertex3f(-bound + (bound * 2) / sz - 0.01f, bound - 0.01f, -5.0f);
//bottom right
glVertex3f(-bound + (bound * 2) / sz - 0.01f, bound - ((bound * 2) / sz) + 0.01f, -5.0f);
//bottom left
glVertex3f(-bound + 0.01f, bound - ((bound * 2) / sz) + 0.01f, -5.0f);
glEnd();

}

Where 'bound' is half of the size of the grid on the screen (the SIZE not the dimensions)
and sz is the dimensions of the grid (10x10, 20x20, etc...)

Now, my problem is that this method doesn't draw the cursor correctly, even with no translation. It ends up looking like this (notice the small green square in the top left corner):

2311

after calling the method like this:

//Where bound and sz are 10 and 1.0 (I inputted those values, and printed them to check)
drawCursor(0.0f, 0.9f, 0.4f, Direction::NONE, bound, sz);

However, the weird thing is that if i copy paste the draw code back into my render() method instead of using it inside the method, effectively using the same variables i passed into the method, it draws correctly:
2312

Why is this, and how do I fix it?
Any help will be appreciated.

Dark Photon
12-25-2016, 01:44 PM
However, the weird thing is that if i copy paste the draw code back into my render() method instead of using it inside the method, effectively using the same variables i passed into the method, it draws correctly: ... Why is this, and how do I fix it?

It would help to see your render method and where you're copy/pasting the drawCursor() internals.