Sign in to follow this  

Ray picking with gluUnProject()

Recommended Posts

I have a quad on the y = -50 plane. At the moment, all I want to do is obtain the coordinates of a mouse click on the quad. I've managed to do this to a limited extent. The problem is that the transformations I applied when drawing the quad aren't accounted for. I can add in some constants and make it work, but I let the user rotate the scene about the x and y axes with glRotatef(), so the coordinates get messed up as soon as a rotation happens.

Here's what I'm doing now:

I call gluUnProject() twice, once with z = 0, and once with z = 1.

gluUnProject( mouseX, WINDOW_HEIGHT - mouseY, 0, modelView, projection, viewport, &x1, &y1, &z1);
gluUnProject( mouseX, WINDOW_HEIGHT - mouseY, 1, modelView, projection, viewport, &x2, &y2, &z2);

Normalized ray vector:

x = x2 - x1;
y = y2 - y1;
z = z2 - z1;
mag = sqrt(x*x + y*y + z*z);
x /= mag;
y /= mag;
z /= mag;

Parametric equation:

float t = -(camY) / y;
planeX = camX + t*x;
planeY = camY + t*y;
planeZ = camZ + t*z;
where (camX, camY, camZ) is the camera position passed to gluLookAt().

I want planeX, planeY, and planeZ to be the coordinates of the click on the quad, in the same coordinate system I used to draw the quad. How can I achieve this?


Share this post

Link to post
Share on other sites
Whatever transformations are used prior to drawing the quad must also be applied to the modelView matrix prior to retrieving it and subsequently using it in your calls to gluUnProject(). For example, assuming the current matrix mode is GL_MODELVIEW, call glPushMatrix(), apply transformations, retrieve your modelView matrix, call glPopMatrix(), and then make your calls to gluUnProject().

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this