处理点击opengl中的3d或2d图

时间:2012-03-26 07:38:42

标签: c++ opengl

如何在opengl中处理特定3d或2d对象的clik,例如我有以下代码

void Widget::drawCircle(float radius) {
    glBegin(GL_TRIANGLE_FAN);
    for (int i = 0; i < 360; i++) {
        float degInRad = i*DEG2RAD;
        glVertex2f(cos(degInRad) * radius, sin(degInRad) * radius);
    }
    glEnd();
}

所以我需要处理点击这个圈子,这个问题是否有任何解决方案?

2 个答案:

答案 0 :(得分:2)

当我需要检测点击时,我通常会进行普通的绘制循环,但不是使用纹理,光照和其他效果绘制对象,而是使用平面/无着色绘制每个对象,每个都使用不同的颜色。然后我检查鼠标所在像素的颜色,然后从帧缓冲区返回的颜色向后映射到我用该颜色绘制的对象。

也许这种技术对你也很有用。

答案 1 :(得分:1)

查看this nehe tutorial item。它非常复杂,但它显示了opengl pick的工作原理。在我看来,如果你需要它,你可以用一些游戏引擎,然后使用opengl。

Here是另一种(类似的)在opengl中选择项目的方式。

opengl mouse raytracing将为您提供如何在opengl中选择项目的所有详细信息。 This thread甚至提供了代码的完成方式:

Vector3 World::projectedMouse(float mx, float my){

    GLdouble model_view[16];
    GLint viewport[4];
    GLdouble projection[16];

    GLfloat winX, winY, winZ;
    GLdouble dx, dy, dz;

    glGetDoublev(GL_MODELVIEW_MATRIX, model_view);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)mx;
    winY = (float)viewport[3] - (float)my;

    glReadPixels ((int)mx, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ); 
    gluUnProject(winX, winY, 0, model_view, projection, viewport, &bx, &by, &bz);
    Vector3 pr2 = Vector3(bx, by, bz);

    glColor3f(1,0,0);
    glBegin (GL_LINE_LOOP); 
    glVertex3f(player->getPosition().x, player->getPosition().y + 100, player->getPosition().z); // 0
    glVertex3f(pr.x,pr.y,pr.z); // 1
    glVertex3f(player->getPosition().x, player->getPosition().y, player->getPosition().z); // 0
    glEnd();

    return pr;
}