# Ray picking gives inversed results

I'm trying to do a simple ray picking implementation to allow a user to select a cell in a grid rendered in 3D. I'm almost there, but I've ran into an issue which I can't seem to solve.

Consider the following image:

The line represents the ray. The circled part is where the mouse is, and the line's green tip is where it intersects with the grid (XZ plane). When I move the mouse around, the green tip moves almost opposite of the mouse.

What is causing this?

I am converting screen coordinates to OpenGL coordinates using gluUnproject.

After obtaining the direction and position of the mouse, I use the properties of similar triangles to obtain the XZ interception. The ratio between the direction y and position y is the same for both x and z axis. Hence multiplying the direction x, z by the ratio and using y=0 should give the location of the XZ plane intersection. Essentially:

Ray ray = ...
float ratio = ray.point.y / ray.dir.y;
Vector3 intercept = new Vector3(ray.dir.x * ratio, 0, ray.dir.z * ratio);


And yet, as the image shows, its not. Is there something wrong with my reasoning, or something I've overlooked?

• Almost opposite? Like just opposite top/bottom or left/right as well? Perhaps the projection you're creating for your picking is not the same as the projection you're creating for your camera. Typically, "find my code error" questions are too localized for the site. – MichaelHouse Jun 14 '13 at 1:23

A couple possible sources of error:

1) Is the double-negative on the Y-axis intentional?

Ray ray = getPickingRay(Mouse.getX(), Display.getHeight() - Mouse.getY());
...
float winY = (float) viewport.get(3) - (float) cursorY;


2) You're ignoring ray.point.x and ray.point.z in the final line

Vec3d intercept = new Vec3d(ray.dir.x * ratio, 0, ray.dir.z * ratio);