如何在 2D opengl 中进行拣选

How to do picking in 2D opengl?

本文关键字:opengl 2D      更新时间:2023-10-16

我想在opengl中选择2d对象,但不知道如何选择。我想要它像3d一样使用gluPickMatrix。这是我尝试过的:

void initDraw2D(){
    GLuint buff[BUFSIZE];                
    GLint hits, view[4];
    glSelectBuffer(BUFSIZE, buff);
    glGetIntegerv(GL_VIEWPORT, view);
    glRenderMode(GL_SELECT);
    glInitNames();
    glPushName(0);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
        glLoadIdentity();
        gluPickMatrix(mouseX, view[3] - mouseY, 1.0, 1.0, view);
        glMatrixMode(GL_MODELVIEW);
        Draw();
        glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    hits = glRenderMode(GL_RENDER);
    if (onSelect){
    processHits(hits, buff);
    onSelect = false;
    }
    Draw();
    glutPostRedisplay();
}

但是当我单击它时它不会选择。

一种简单的方法是用不同的颜色渲染每个对象。编写一个返回三维数组(vector)的函数,如果尚未选择,则选择它作为对象的选择颜色,添加到选择颜色列表中。所以现在每个对象都有不同的颜色,你可以在光标的位置检查像素的颜色。为此,请使用帧缓冲或 pbo-s。然后在选择列表中进行查找,并返回指向该对象的指针。(或者用它做任何你想做的事情)。

当然,它不必在屏幕上呈现。

它看起来像这样:(伪代码)

object* object1 = new object();
object1->createSelectColor();
object1->addColorToList();
...

objectRenderer->renderColoredObjects(/*to the fbo or texture for example*/);
objectRenderer->pickColorAtCursorPos();
objectRenderer->lookUpColorInList(/*objectRenderer->selectedcolor*/);
objectRenderer->setTarget(/*objectRenderer->selectedobject*/);

这与几何无关。R、G 和 B 的颜色范围为 0-255。所以这是255 * 255 * 255=16581375不同的颜色,每个对象一个。

您可以为颜色查找创建地图,索引对象和颜色,创建巧妙的颜色选择功能,使查找变得容易......等。

这种方法可以在书中找到:Chris Seddon-OpenGL游戏开发,这是一个非常好的开始。

你不能只检查鼠标光标是否在边界矩形内吗?

class Rectangle
{
    int x, y, w, h;
    bool IsPicked(Point mousePos)
    {
       return ((mousePos.x >= x) && (mousePos.x <= x + w)) 
              && 
              ((mousePos.y >= y) && (mousePos.y <= y + h));
    }
};

(用心写的,没有测试=)