不确定这是否对您有帮助,但我以这种方式实现了光线拾取(计算光线的方向):
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.