I'm trying for long time to implement picking ray.
I read lots of tutorials online, but still did not managed to make to work properly.
I'm created the near/far points using unproject method ( that works exactly the same as gluunproject does).
then I created the ray and check for intersection with the bounding box.
For visual reference I draw the ray. it looks like the ray does not comes out from the mouse cursor toward the scene.
Please help me in here.
tnx
int UnProject(float winx, float winy, float winz, const Matrix4f *modelview, const Matrix4f *projection, int viewport[4], Vector3f *objectCoordinate)
{
const m44<f32>& inverseVP = (*projection * *modelview).inverse();
Vector4f in( (winx-(float)viewport[0])/(float)viewport[2]*2.0-1.0,
(winy-(float)viewport[1])/(float)viewport[3]*2.0-1.0,
2.0*winz-1.0,
1.0 );
Vector4f out = inverseVP * in;
if(out.w == 0.0f)
return 0;
out[3]=1.0/out[3];
objectCoordinate->x=out.x*out.w;
objectCoordinate->y=out.y*out.w;
objectCoordinate->z=out.z*out.w;
return 1;
}
void sRay::Create( const int& MouseX,
const int& MouseY,
NS_CAMERA::sCamera* pCamera )
{
int viewport[4] = {0,0,WINDOW_WIDTH, WINDOW_HIGHT };
Vector3f _near;
Vector3f _far;
UnProject(MouseX, viewport[3]-MouseY,0,&pCamera->GetViewMatrix(),&pCamera->GetProjectionMatrix(),viewport,&_near); // get coords
UnProject(MouseX, viewport[3]-MouseY,1,&pCamera->GetViewMatrix(),&pCamera->GetProjectionMatrix(),viewport,&_far);
m_Direction = (_far - _near).normalize();
m_Origen = *pCamera->GetCameraPos();
}
void sRay::Render( NS_CAMERA::sCamera* pCamera )
{
Vector3f p0 = m_Origen;
Vector3f p1 = pCamera->fZFar *m_Direction;
// Drawing the line using OGL...
}