0
\$\begingroup\$

I've run into a curious issue when implementing ray picking in my game engine. It seems the Z coordinate of the Projected matrix has to be ever so slightly more than 1.0f.

I was having some issues when doing ray-triangle picking. When trying to pick an object, the cursor was just a few pixels off from where the ray would end up going. I tried looking for a pattern (if it got more off the further from the center, à la FOV/perspective projection issue) but couldn't find one.

I made sure that all changes to the perspective matrix throughout the code base were the exact same (specifically the near and far planes).

I finally started messing around with the Z coordinate of the projected vector. I had it as 1.0f, but after trial and error, changed it to 1.00001f and now everything works great, and the ray-picking is super accurate.

Here is my code for generating the world coordinates (ctx is the renderer context that holds relevant information like the projection matrix, width/height, etc.):

glm::vec4 viewport(0.0f, 0.0f, ctx.width, ctx.height);
glm::mat4 projection = ctx.projection;
glm::mat4 model_view = camera.get_view_matrix();
glm::vec3 projected = {
    mouse.x,
    ctx.height - mouse.y,
    1.00001f
};

glm::vec3 unprojected = glm::normalize(glm::unProject(projected, model_view, projection, viewport));

When I change the projected vector to:

glm::vec3 projected = {
    mouse.x,
    ctx.height - mouse.y,
    1.0f
};

everything seems to be slightly off. I'm wondering if there's an explanation as to what could be causing this? Surely it wouldn't just be a floating point rounding error, but I can't seem to find another reason.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I believe I found a solution here. The solution was actually calculating the near plane (where Z = 0) and the far plane (Z = 1...what I'm currently doing) and subtracting them. I was experiencing the same phenomena as the linked thread.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .