3D Ray Picking use Mouse Coordinates when Mouse isn't locked

流过昼夜 提交于 2019-11-28 08:30:37

here is my code for creating a mouse ray:

double matModelView[16], matProjection[16]; 
int viewport[4]; 

// get matrix and viewport:
glGetDoublev( GL_MODELVIEW_MATRIX, matModelView ); 
glGetDoublev( GL_PROJECTION_MATRIX, matProjection ); 
glGetIntegerv( GL_VIEWPORT, viewport ); 

// window pos of mouse, Y is inverted on Windows
double winX = (double)mouseX; 
double winY = viewport[3] - (double)mouseY; 

// get point on the 'near' plane (third param is set to 0.0)
gluUnProject(winX, winY, 0.0, matModelView, matProjection, 
         viewport, m_start.x, &m_start.y, &m_start.z); 

// get point on the 'far' plane (third param is set to 1.0)
gluUnProject(winX, winY, 1.0, matModelView, matProjection, 
         viewport, m_end.x, &m_end.y, &m_end.z); 

// now you can create a ray from m_start to m_end

OpenGL 2.0, but hope you get the idea.

Some links: Select + Mouse + OpenGL

All you need to do is shoot a ray out from the camera's origin that passes through the screen space point (x,y). The problem here is that to get from your camera's origin to a point in screen space there are a number of transformations that usually occur (2 matrices and a viewport mapping in fact). The other problem is that this throws everything on its head, usually you start with a world space position and wind up with screen space in the OpenGL pipeline -- you want to go the other way :)

You cannot solve this problem with the camera's orientation alone. You need to know how the scene is projected onto your viewing plane, hence the need for the projection matrix. You also need to know the viewport dimensions and the camera's origin. The entire problem can be solved if you know the viewport dimensions, the projection matrix and the modelview matrix.

I would suggest you look into gluUnProject (...), it does everything you need. A quick search on Google resulted in this, which looks pretty helpful: http://myweb.lmu.edu/dondi/share/cg/unproject-explained.pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!