0) Obtain your mouse coordinates within the client area
1) Get your Projection matrix and View matrix if no Model matrix required.
2) Multiply View * Projection
3) Inverse the results of multiplication
4) Construct a vector4 consisting of
x = mouseposition.x
within a range of window x - transform to values between -1 and 1
y = mouseposition.y
within a range of window y - transform to values between -1 and 1 - remember to invert mouseposition.y if needed
z = the depth value
( this can be obtained with glReadPixel) - you can manually go from -1 to 1 ( zNear, zFar )
w = 1.0
5) Multiply the vector by inversed matrix created before 6) Divide result vector by it's w component after matrix multiplication ( perspective division )
1
POINT mousePos;
2
GetCursorPos(&mousePos);
3
ScreenToClient( this->GetWindowHWND(), &mousePos );
4
5
CMatrix4x4 matProjection = m_pCamera->getViewMatrix() * m_pCamera->getProjectionMatrix() ;
6
7
CMatrix4x4 matInverse = matProjection.inverse();
8
9
float in[4];
10
float winZ = 1.0;
11
12
13
in[0]=(2.0f*((float)(mousePos.x-0)/(this->GetResolution().x-0)))-1.0f,
14
in[1]=1.0f-(2.0f*((float)(mousePos.y-0)/(this->GetResolution().y-0)));
15
in[2]=2.0* winZ -1.0;
16
in[3]=1.0;
17
18
CVector4 vIn = CVector4(in[0],in[1],in[2],in[3]);
19
pos = vIn * matInverse;
20
21
pos.w = 1.0 / pos.w;
22
23
pos.x *= pos.w;
24
pos.y *= pos.w;
25
pos.z *= pos.w;
26
27
sprintf(strTitle,"%f %f %f / %f,%f,%f ",m_pCamera->m_vPosition.x,m_pCamera->m_vPosition.y,m_pCamera->m_vPosition.z,pos.x,pos.y,pos.z);
28
29
SetWindowText(this->GetWindowHWND(),strTitle);
参考文章:http://stackoverflow.com/questions/7692988/opengl-math-projecting-screen-space-to-world-space-coords-solved?answertab=active#tab-top