OpenGL C++ 鼠标光线拾取 glm:unproject

2024-04-15

我目前正在开发 C++ 游戏引擎,我想在应用程序中构建鼠标交互。我之前通过光线拾取完成了此操作,但当时我使用了固定的鼠标位置,现在我想不使用它。我读到您可以使用 glm::unProject 函数来执行此操作,但我的函数不起作用。该函数给出的坐标不正确。我究竟做错了什么?

rscore_projection_matrix = glm::perspective(45.0f, (float)(windowWidth)/(float)(windowHeight), 0.1f, 1000.0f);
rscore_view_matrix = glm::lookAt(glm::vec3(lengthdir_x(16, rscam_direction)+rscam_x, rscam_z, lengthdir_y(16, rscam_direction)+rscam_y), glm::vec3(rscam_x, 0, rscam_y), glm::vec3(0,1,0));
rscore_model_matrix = glm::mat4(1.0f);
glm::vec3 screenPos = glm::vec3(rscore_mouse_x, rscore_mouse_y, 0.1f);
glm::vec4 viewport = glm::vec4(0.0f, 0.0f, windowWidth, windowHeight);
glm::vec3 worldPos = glm::unProject(screenPos, rscore_model_matrix, rscore_projection_matrix, viewport);

我使用 vec3 worldPos 位置来绘制对象。


不确定这是否对您有帮助,但我以这种方式实现了光线拾取(计算光线的方向):

glm::vec3 CFreeCamera::CreateRay() {
    // these positions must be in range [-1, 1] (!!!), not [0, width] and [0, height]
    float mouseX = getMousePositionX() / (getWindowWidth()  * 0.5f) - 1.0f;
    float mouseY = getMousePositionY() / (getWindowHeight() * 0.5f) - 1.0f;

    glm::mat4 proj = glm::perspective(FoV, AspectRatio, Near, Far);
    glm::mat4 view = glm::lookAt(glm::vec3(0.0f), CameraDirection, CameraUpVector);

    glm::mat4 invVP = glm::inverse(proj * view);
    glm::vec4 screenPos = glm::vec4(mouseX, -mouseY, 1.0f, 1.0f);
    glm::vec4 worldPos = invVP * screenPos;

    glm::vec3 dir = glm::normalize(glm::vec3(worldPos));

    return dir;
}

// Values you might be interested:
glm::vec3 cameraPosition; // some camera position, this is supplied by you
glm::vec3 rayDirection = CFreeCamera::CreateRay();
glm::vec3 rayStartPositon = cameraPosition;
glm::vec3 rayEndPosition = rayStartPosition + rayDirection * someDistance;

解释:

当您将顶点的位置与视图和投影矩阵相乘时,您将获得像素位置。如果将像素位置与视图和投影矩阵的逆相乘,则可以得到世界位置。

虽然计算逆矩阵很昂贵,但我不确定 glm::unProject 是如何工作的,它可能会做同样的事情。

这只会为您提供面向世界的光线方向(并且您应该已经知道相机的位置)。此代码不会与对象发生“碰撞”。

相机类的其余代码是here https://github.com/RippeR37/Stay-Sharp/blob/master/Renderer/FreeCamera.cpp.

更多信息可以找到 - 例如 -here http://antongerdelan.net/opengl/raycasting.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OpenGL C++ 鼠标光线拾取 glm:unproject 的相关文章

随机推荐