我试图在2D平面上获得2d世界坐标(Z = 0),我在3D场景中用鼠标点击。我发现光线投射可能是最好的方法。
这段代码是我从互联网上搜集出来的:
glm::vec3 Drawer::MouseToWorldCoords(glm::vec2 coords)
{
//getting camera position
glm::mat3 rotMat(view);
glm::vec3 d(view[3]);
glm::vec3 retVec = -d * rotMat;
//std::cout << " x " << retVec.x << " y " << retVec.y << " z " << retVec.z << std::endl;
//getting mouse coords
float x = 2.0 * coords.x / WINDOW_WIDTH - 1;
float y = -2.0 * coords.y / WINDOW_HEIGHT + 1;
float z = -1.0f;
//raycasting
glm::vec4 ray(x, y, z,1.0f);
glm::vec4 ray_eye = inverse(proj) * ray;
ray_eye = glm::vec4(ray_eye.x,ray_eye.y, 1.0, 0.0);
glm::vec3 ray_world = glm::vec3((glm::inverse(view) * ray_eye));
ray_world = glm::normalize(ray_world);
//intersecting plane with ray
glm::vec3 ba = retVec - ray_world ;
float nDotA = glm::dot(glm::vec3(0.0f,0.0f,1.0f), ray_world);
float nDotBA = glm::dot(glm::vec3(0.0f,0.0f,1.0f), ba);
glm::vec3 intersect = (ray_world + (((0.0f - nDotA) / nDotBA) * ba)) ;
return glm::vec3( -intersect.x * 10.0f,-intersect.y * 10.0f,0.0f );
}
这段代码不能按照应有的方式运行。正如您在图片中看到的那样:
程序只是在函数返回的位置生成多维数据集。为了产生这个结果,我只点击了屏幕边缘(当然中间的2除外)。