Ben Tanos Ben Tanos - 1 month ago 7
C++ Question

OpenGL - Calling square function with different colour

I have made a

drawSquare()
function that draws several 2D squares on my screen:

void drawSquare(GLfloat length, GLfloat x, GLfloat y, GLfloat outline){
// x1,y1 is the top left-hand corner coordinate
// and so on...
GLfloat x1, y1, x2, y2, x3, y3, x4, y4;

x1 = x - length / 2;
y1 = y + length / 2;
x2 = x + length / 2;
y2 = y + length / 2;
x3 = x + length / 2;
y3 = y - length / 2;
x4 = x - length / 2;
y4 = y - length / 2;

// ACTUAL SQUARE OBJECT
glColor3f(0.0, 1.0, 1.0); // Colour: Cyan
glBegin(GL_POLYGON);
glVertex2f(x1, y1); // vertex for BLUE SQUARES
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glEnd()
}


When I click a square, I need its colour to change. I already have a mouse function set up that displays the mouse location when I right click:

void processMouse(int button, int state, int x, int y)
{
if ((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN)){
// gets mouse location
printf("Clicked on pixel %d - %d", x, y);
// prints to console
}
}


and an
if statement
inside the above
if statement
like this:

if (x > 0 && x < 95 && y > 302 && y < 395) {
// there's a square at this location!
// change the square colour!
}


When I place
exit(0);
inside this statement:

if (x > 0 && x < 95 && y > 302 && y < 395) {
exit(0);
}


My program exits fine, so the condition works, I just want to know how I can somehow call my
drawSquare()
function again with a different colour
.

Initially when I call my
drawSquare()
, it's called in my display function like this:

void display(){
glClear(GL_COLOR_BUFFER_BIT); /* clear window */
// there are some other primatives here too
drawSquare(100,150, 750,true); // square drawn
}

Answer

In your event handler set a variable, then trigger a redraw.

if (x > 0 && x < 95 && y > 302 && y < 395) { 
            // there's a square at this location!
            // change the square colour!
            square_color = ...;
            glutPostRedisplay();
}

In your display function check for the variable and use that to determine the color:

// you should probably make the color a parameter of drawSquare
void drawSquare(GLfloat length, GLfloat x, GLfloat y, GLfloat outline){

    // OpenGL doesn't do "objects". It **DRAWS** things. Like pen on paper

    glColor3f(square_color); // <---- uses variable
    glBegin(GL_POLYGON);
...
    glEnd()
}