OpenGL -调用不同颜色的平方函数

OpenGL - Calling square function with different colour

本文关键字:方函数 函数 调用 颜色 OpenGL      更新时间:2023-10-16

我制作了一个drawSquare()函数,它在我的屏幕上绘制了几个2D正方形:

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()
}

当我点击一个正方形时,我需要改变它的颜色。我已经设置了一个鼠标功能,当我右键单击时显示鼠标位置:

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
    }
}

if statement在上面的if statement中,像这样:

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

当我将exit(0);放入语句中时:

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

我的程序退出很好,所以条件工作,我只是想知道我如何以某种方式再次调用我的drawSquare()函数与不同的颜色

最初,当我调用drawSquare()时,它在我的显示函数中被调用,像这样:

void display(){
    glClear(GL_COLOR_BUFFER_BIT);   /* clear window */
    // there are some other primatives here too
    drawSquare(100,150, 750,true);  // square drawn
}
<<p> 解决方案/strong>

这是我如何解决我的问题。我做了一个全局布尔变量布尔变量areaClicked = false;检查用户是否点击,我们默认设置为false。

在我的鼠标函数中,我检查一个正方形是否被点击,如果是,设置布尔值为true:

if (x >= 0 && x <= 95 && y >= 302 && y <= 380) { // area of box
            areaClicked = true;
} 

现在在我的display函数中,我们检查布尔值是否被触发,如果是,那么显示我的重新着色的正方形,否则什么都不做:

if (areaClicked != false) {
        drawRecolour(100, 50, 350, true);   // 4th square drawn
}
else areaClicked = false;

在事件处理程序中设置一个变量,然后触发重绘。

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

在您的显示函数中检查变量并使用它来确定颜色:

// 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()
}