在OpenGL中检测鼠标位置/点击对象的最佳方法是什么?

时间:2010-10-12 19:21:04

标签: opengl

我正在创建一个简单的2D OpenGL游戏,我需要知道玩家何时点击或鼠标悬停在OpenGL原语上。 (例如,在作为其中一个图块的GL_QUADS上...)似乎没有一种简单的方法可以做到这一点,除了暴力或者opengl.org建议为我的每个图元使用唯一的颜色,这似乎有点hacky。我错过了什么吗?感谢...

3 个答案:

答案 0 :(得分:6)

我的建议是,不要使用OpenGL的选择模式或OpenGL渲染(你正在谈论的强力方法),如果使用3D,则使用基于CPU的光线拾取算法。对于2D,就像你的情况一样,它应该是直截了当的,它只是一个测试,知道2D点是否在2D矩形中。

答案 1 :(得分:2)

如果你想快速实现(编码时间,我的意思是),我建议使用hacky方法。特别是如果您不想实现具有移动对象的四叉树。如果您使用的是opengl立即模式,那应该很简单:

// Rendering part
glClearColor(0,0,0,0);
glClear(GL_COLOR_BUFFER_BIT);
for(unsigned i=0; i<tileCout; ++i){
    unsigned tileId = i+1; // we inc the tile ID in order not to pick up the black
    glColor3ub(tileId &0xFF, (tileId >>8)&0xFF, (tileId >>16)&0xFF);
    renderTileWithoutColorNorTextures(i);
}

// Let's retrieve the tile ID
unsigned tileId = 0;
glReadPixels(mouseX, mouseY, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE,
             (unsigned char *)&tileId);
if(tileId!=0){  // if we didn't picked the black 
    tileId--;
    // we picked the tile number tileId
}

// We don't want to show that to the user, so we clean the screen
glClearColor(...); // the color you want
glClear(GL_COLOR_BUFFER_BIT);

// Now, render your real scene
// ...
// And we swap
whateverSwapBuffers(); // might be glutSwapBuffers, glx, ...

答案 2 :(得分:1)

您可以使用OpenGL的glRenderMode(GL_SELECT)模式。使用它的Here is some code,应该很容易理解(查找_pick方法)

(这里是same code在C中使用GL_SELECT

(过去有一些案例 - GL_SELECT 故意放慢'非工作站'卡片以阻止CAD并建模用户购买消费者3D卡片;这应该是ATI和NVidia已经成长的过去的坏习惯;))