1

I've been working on mouse picker on a OpenGL project and followed this guide to transform my 2D mouse position to a 3D vector on click.

The problem I have is in my calculations for picking the object/mesh. It seems to work properly if I am in the origin position of the camera, but as soon as I start to move around with the camera my calculated bounding sphere for the mesh gets out of position. I assume that I need to do some kind of matrix transformation to fix this problem but I can't figure it out. I do have access to the view matrix but I'm not sure If I should implement it in my calculations.

A video of my problem. It can be a bit hard to understand the problem with no click sounds. It gets more visually clear towards the end when I am able to select the object by clicking next to it.

Data I have for calculations:

  • The position of the camera (rayOrigin in calculations)
  • The mesh and all of its vertices and also the position of the mesh in world space.
  • The 3D vector for the mouse click calculated with the same method as the guide mentioned above.

The first thing I've done is to re-calculate all the objects vertices to fit the position of the mesh in world space. The position of the mesh should also be the center of the mesh (at least in the video I linked earlier).

vertecies[i] = vec3(worldMatrix * vec4(vertecies[i], 1));

In my second step I compare each vertex with the center position and calculate which vertex that has the largest magnitude from the center. This vectors lenght I use as radius for my bounding sphere.

My calculations for the bounding sphere ray test, rayDir is the mouse position vector, rayOrigin is the camera position:

vec3 oc = rayOrigin - center;
float doc = dot(oc , rayDir);

if (doc > 0 || (dot(doc, doc) < radiusSquared)) return false; // no hit

vec3 a = oc - doc * rayDir;
float aSquared = dot(a, a);

if (aSquared > radiusSquared) return false; // no hit

return true; // hit

My linear algebra isn't the best so I'm hoping you guys can help me out and tell me what I do wrong here.

4

1 回答 1

0

我一直在看这个问题,但指的是这个网页。从开发人员的角度来看,我发现您的参考很难遵循,而且您的数学与我的参考不一致。例如,您的第一个条件应该是:

if (doc < 0) return false;

我不会研究你的代码来看看它在数学上是否等价。但是,我建议您从参考资料底部的代码开始。此外,验证center球的中心是否与您的射线在同一坐标系中。

作为旁注:

当我遇到此类问题时,它总是可以帮助我在场景中画线。在这种情况下,我会将光线转换为世界空间,并且不要忘记相机眼睛(在世界空间中)是从逆视图矩阵中提取的。我更喜欢直接将它从逆向中拉出来,所以我不必质疑我是否依赖过时的缓存数据。

于 2018-07-21T00:38:55.787 回答